1.
有向图中反向图构造
。对
tinyDG.txt
(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。
类名
:
GraphReverse
。
package com.GraphR;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
/*
* @authorzhangweiwei
*/
public class GraphReverse {
private int vNum;
private int arcNum;
private boolean visited[];
private List<ArrayList<Integer>> graphListS;
private List<ArrayList<Integer>> graphListF;
public GraphReverse(int vNum,int arcNum,List<ArrayList<Integer>> graphListS,List<ArrayList<Integer>> graphListF){
this.vNum=vNum;
this.graphListS=graphListS;
visited=new boolean[vNum];
this.graphListF=graphListF;
}
public static void main(String[] args) {
String path="src/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 vNum=scanner.nextInt();
int arcNum=scanner.nextInt();
for(int i=0;i<vNum;i++){
graphListS.add(new ArrayList<Integer>());
graphListF.add(new ArrayList<Integer>());
}
//有向图的存储
for(int i=0;i<arcNum;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(vNum, arcNum, graphListS,null);
System.out.println("有向图的邻接表的结果是:");
g1.bfs(vNum/2+1,graphListS);
//有向图的反向图广度优先的遍历
GraphReverse g2=new GraphReverse(vNum, arcNum, null,graphListF);
System.out.println("有向图的反向图的邻接表结果是:");
g2.bfs(1,graphListF);
}catch (Exception e) {
e.printStackTrace();
}
}
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.add(k);
que.offer(k);
visited[k] = true;
}
}
System.out.println();
}
}
}
有向图的邻接表的结果是:
7:9 6
9:10 11
6:0 8 4 9
10:12
11:12 4
0:1 5
8:6
4:2 3
12:9
1:
5:4
2:3 0
3:2 5
有向图的反向图的邻接表结果是:
1:0
0:6 2
6:8 7
2:4 3
8:6
7:
4:11 5 6
3:2 4