您的位置:首页 > 其它

第五周作业——有向图邻接表表示及反向图构造

2014-04-11 20:32 411 查看
有向图中反向图构造。对tinyDG.txt(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。

邻接表表示示例如下:

0:1 5

1:

2:0 3

……



代码如下:

public class
MyVertex {

int data;

Edge adj;

}

public class Edge {

int dest;

Edge link;

Edge(int D)

{

dest=D;

link=null;

}

}

import
java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

public class GraphReverse {

public static void main(String args []){

String path = "F:\\tinyDG.txt";

ArrayList<Integer> list = read(path);

int vn=list.get(0);//图的顶点数

int en=list.get(1);//图的边数

int b[][] = new int[list.get(1)][2];

int v[] = new int[list.size()];//顶点数组

for(int i=0;i<vn;i++){//顶点数组初始化

v[i]=i;

}

//反向图的邻接表

/*int k=(list.get(1)+1)*2-1; //最后一个

for(int i=0;i<list.get(1);i++){

for(int j=0;j<2;j++){

b[i][j]=list.get(k);

k--;

}

}*/

//图的邻接表

int k=2; //最后一个

//将一位数组的值加入到二维数组中

for(int i=0;i<list.get(1);i++){

for(int j=0;j<2;j++){

b[i][j]=list.get(k);

k++;

}

}

GraphReverse G=new GraphReverse();

G.Graphadj(vn, v, en, b);

G.display();

}

static int DefalutSize=20;

private Vertex NodeTable[];

private int NumVertices=0;

private int NumEdges=0;

public void Graphadj(int vn,int v[],int en,int e[][]){

NodeTable=new Vertex[vn];

for(int i=0;i<vn;i++){

InsertVertex(v[i]);

}

for(int i=0;i<en;i++)

{

InsertEdge(e[i][0],e[i][1]);

}

}

public boolean InsertVertex(int vertex)

{

Vertex t=new Vertex();

t.data=vertex;

t.adj=null;

NodeTable[NumVertices]=t;

NumVertices++;

return true;

}

public boolean InsertEdge(int v1,int v2){

if(v1>NumVertices||v1<0)

return false;

if(v2>NumVertices||v2<0)

return false;

Edge E=new Edge(v2);

Edge p=NodeTable[v1].adj;

if(p==null)

NodeTable[v1].adj=E;

else{

while(p.link!=null) p=p.link;

p.link=E;

}

NumEdges++;

return true;

}

public void display(){

Edge p;

for(int i=0;i<NumVertices;i++){

System.out.print(NodeTable[i].data+":");

p=NodeTable[i].adj;

while(p!=null)

{

System.out.print(p.dest+" ");

p=p.link;

}

System.out.println();

}

}

public static ArrayList read(String path) {

ArrayList<Integer> list = new ArrayList<Integer>();

BufferedReader input = null;

try {

FileReader in = new FileReader(path);

input = new BufferedReader(in);

String ss;

try {

while ((ss = input.readLine()) != null) {

String[] s = (ss.split(" "));

for (int i = 0; i < s.length; i++) {

list.add(Integer.parseInt(s[i].trim())); // 将String

// s中的内容添加到动态数组中

}

}

} catch (IOException e) {

e.printStackTrace();

}

in.close();

input.close();

} catch (Exception e) {

e.printStackTrace();

}

return list;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: