06-图1 列出连通集 JAVA实现
题目
给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。随后E行,每行给出一条边的两个端点。每行中的数字之间用1空格分隔。
输出格式:
按照"{ v
1
v
2
… v
k
}"的格式,每行输出一个连通集。先输出DFS的结果,再输出BFS的结果。
输入样例:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
输出样例:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }
public class ConnectedSet {
private static int Vex;
private static int Edge;
private static int[][] node=new int[Vex][Vex];
private static boolean[] visit=new boolean[Vex];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Vex=sc.nextInt(); //顶点个数
Edge=sc.nextInt(); //边条数
node =new int[Vex][Vex]; //定义一个矩阵记录顶点之间是否连通
visit=new boolean[Vex]; //记录是否被访问过
for(int i=0;i<Vex;i++) { //矩阵初始化
for(int j=0;j<Vex;j++) {
node[i][j]=0;
}
}
int tmp_v1;
int tmp_v2;
for(int k=0;k<Edge;k++) { //读取顶点之间的连接关系;
tmp_v1=sc.nextInt();
tmp_v2=sc.nextInt();
node[tmp_v1][tmp_v2]=1;
node[tmp_v2][tmp_v1]=1;
}
reset(visit); //初始化访问,全部设置为false
//使用深度优先搜索,输出
for(int d=0;d<Vex;d++) { //保证每个顶点都被访问过
if(visit[d]==false) {
System.out.print("{ ");
DFS(d);
System.out.println("}");
}
}
reset(visit); //重新初始化为false
//使用广度优先搜索,输出
for(int v=0;v<Vex;v++) {
if(!visit[v]) {
System.out.print("{ ");
BFS(v);
System.out.println("}");
}
}
}
public static void BFS(int v) {
visit[v]=true; //顶点被访问
Queue<Integer> queue=new LinkedList<>(); //使用队列存放相邻顶点
queue.add(v); //顶点放入队列
while(!queue.isEmpty()) {
int tmp=queue.poll(); // 弹出顶点
System.out.print(tmp+" ");
for(int n=0;n<Vex;n++) { //遍历相邻顶点
if(node[tmp][n]!=0 && visit[n]==false) {
queue.add(n); //相邻顶点加入到队列;
visit[n]=true; //已被访问
}
}
}
}
public static void DFS(int v) {
visit[v]=true; //访问顶点
System.out.print(v+" ");
for(int m=0;m<Vex;m++) { //使用递归不断访问相邻顶点;
if(node[v][m]!=0 && visit[m]==false) {
DFS(m);
}
}
}
public static void reset(boolean[] visit) { //初始化visit
for(int c=0;c<visit.length;c++) {
visit[c]=false;
}
}
}