连通图
题目描述
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入格式
每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。如果 n 为 0 表示输入结束。随后有 m 行数据,每行有两个值 x 和 y(0<x, y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。
输出格式
对于每组输入数据,如果所有顶点都是连通的,输出"YES",否则输出"NO"。
样例输入
4 3
4 3
1 2
1 3
5 7
3 5
2 3
1 3
3 2
2 5
3 4
4 1
7 3
6 2
3 1
5 6
0 0
样例输出
YES
YES
NO
代码如下
import java.util.Scanner;
public class Main{
int[] father;
int find(int x){
if(father[x] == x) return x;
return father[x] = find(father[x]);
}
void merge(int x, int y){
int a = find(x);
int b = find(y);
if(a != b){
father[a] = b;
}
}
public static void main(String[] args) {
Main main = new Main();
Scanner sc = new Scanner(System.in);
while(true) {
int n = sc.nextInt();
int m = sc.nextInt();
if(n == 0)
break;
main.father = new int[n+1];
for(int i = 1; i <= n; i++){
main.father[i] = i;
}
for(int i = 0; i < m; i++){
int x = sc.nextInt();
int y = sc.nextInt();
main.merge(x, y);
}
int count = 0;
for(int i = 1; i <= n; i++){
if(main.father[i] == i)
count++;
}
if(count == 1)
System.out.println("YES");
else
System.out.println("NO");
}
sc.close();
}
}