1. 有向图中反向图构造。对tinyDG.txt(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。类名:GraphReverse。
邻接表表示示例如下:
0:1 5
1:
2:0 3
……
====
package alsys5_1;
import java.io.*;
import java.util.*;
public class GraphReverse {
private int vertex;//有向图顶点
private int edge;//有向图边
private boolean visited[];
private List<ArrayList<Integer>> graphListS;//有向图
private List<ArrayList<Integer>> graphListF;//有向图的反向图
//构造函数
public GraphReverse(int vertex,int edge,List<ArrayList<Integer>> graphListS,List<ArrayList<Integer>> graphListF){
this.vertex=vertex;
visited=new boolean[vertex];
this.graphListS=graphListS;
this.graphListF=graphListF;
}
//广度优先遍历生成邻接表
private void BFS(int v,List<ArrayList<Integer>> graphList){
Queue<Integer> que=new LinkedList<Integer>();//导入数组队列
que.offer(v);//插入顶点
while(!que.isEmpty()){
v=que.poll();//检索队列
System.out.print(v+":");//邻接表
visited[v]=true;
for(int i=0;i<graphList.get(v).size();i++){
int k=graphList.get(v).get(i);
System.out.print(k+" ");
if(!visited[k]){
que.offer(k);
visited[k]=true;
}
}
System.out.println();
}
}
public static void main(String[] args){
String path="e:/tinyDG.txt";
try{
Scanner scanner=new Scanner(new File(path));
List<ArrayList<Integer>> graphListS=new ArrayList<ArrayList<Integer>>();//有向图的存储
List<ArrayList<Integer>> graphListF=new ArrayList<ArrayList<Integer>>();//有向图的反向图的存储
int vertex=scanner.nextInt();
int edge=scanner.nextInt();
//有向图构造
for(int i=0;i<vertex;i++){
graphListS.add(new ArrayList<Integer>());
graphListF.add(new ArrayList<Integer>());
}
//有向图的反向图构造
for(int i=0;i<edge;i++){
int u=scanner.nextInt();
int v=scanner.nextInt();
if(!graphListS.get(u).contains(v)){
graphListS.get(u).add(v);
}
if(!graphListF.get(v).contains(u)){
graphListF.get(v).add(u);
}
}
GraphReverse g1=new GraphReverse(vertex,edge,graphListS,null);
System.out.println("有向图的邻接表的结果是: ");
g1.BFS(vertex/2+1,graphListS);
GraphReverse g2=new GraphReverse(vertex,edge,null,graphListF);
System.out.println("有向图的反向图的邻接表结果是 : ");
g2.BFS(1,graphListF);
}catch(Exception e){
e.printStackTrace();
}
}
}
====