KY175 连通图(用Java实现)

描述

    给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。

输入描述:

    每组数据的第一行是两个整数 n 和 m(0<=n<=1000)。n 表示图的顶点数目,m 表示图中边的数目。随后有 m 行数据,每行有两个值 x 和 y(0<x, y <=n),表示顶点 x 和 y 相连,顶点的编号从 1 开始计算。输入不保证这些边是否重复。

输出描述:

    对于每组输入数据,如果所有顶点都是连通的,输出"YES",否则输出"NO"。

示例1

输入:

4 3
1 2
2 3
3 2
3 2
1 2
2 3
0 0

输出:

NO
YES

代码如下

import java.util.Scanner;


/*
 * 连通图
 */
public class ConnectionPhoto {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		OuterLoop:
		while (scanner.hasNext()) {
			
			//n表示图的顶点数
			int n = scanner.nextInt();
			//m表示边的数目
			int m = scanner.nextInt();
			
			if (m == 0||n == 0) {
				break;
			}

			UnionFind uf = new UnionFind(n);
			
			for (int i = 0; i < m; i++) {
				
				//连接边的两个顶点
				int x = scanner.nextInt();	
				int y = scanner.nextInt();
				uf.Union(x, y);
			}
			
			//找到第一个节点的父亲结点
			int root = uf.find(1);
			for (int i = 1; i <= n; i++) {
				if (uf.find(i) == root) {
					//如果所有结点的根结点都相同,则说明所有元素在一个集合中
					continue;
				}else {
					//只要有一个结点的根结点与第一个节点不同,则说明有元素和其他元素不在同一个集合中
					System.out.println("NO");
					//跳出最外层循环
					continue OuterLoop;
				}
			}
			System.out.println("YES");
			
			
		}
	}
}

class UnionFind{
	 
	int[] height;
	int[] parent;
	
	public UnionFind(int n) {

		height = new int[n+1];
		parent = new int[n+1];
		for (int i = 1; i < n+1; i++) {
			height[i] = 0;
			parent[i] = i;
		}
	}
	
	//查操作
	public int find(int i) {	//找到根结点
		if (parent[i] != i) {
			parent[i] = find(parent[i]);
		}
		return parent[i];
	}
	
	//合并操作
	public void Union(int x,int y){
		
		int rootX = find(x);
		int rootY = find(y);
		
		if (rootX == rootY) {
			return;
		}
		
		if (height[rootX] > height[rootY]) {
			parent[rootY] = rootX;
		}else if (height[rootX] < height[rootY]) {
			parent[rootX] = rootY;
		}else {

			parent[rootY] = rootX;
			height[rootX]++;
			
		}
			
	}
	
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Laz124519

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值