LeetCode547. Friend Circles并查集

本文详细介绍了并查集算法的基本概念及其在社交网络中寻找朋友圈的应用。通过具体实现代码展示了如何利用并查集来合并相互关联的朋友圈,并最终确定独立朋友圈的数量。提供了具体的测试用例以验证算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并查集介绍参考:

https://juejin.im/entry/5922593d44d904006cd20175

http://dongxicheng.org/structure/union-find-set/

实现代码:

class Solution {
	public int findCircleNum(int[][] num) {
		// 最初朋友圈的个数
		int count = num.length;
		int father[] = new int[num.length];
		// 存储每个节点的秩
		int rank[] = new int[num.length];
		// 初始化父节点,father[x]=y表示x的父节点是y
		for (int i = 0; i < father.length; i++) {
			father[i] = i;
		}
		for (int i = 0; i < father.length; i++) {
			for (int j = 0; j <= i; j++) {
				if (num[i][j] == 1)
					count = Union(father, rank, i, j, count);
			}
		}
		return count;
	}

	int find(int[] father, int x) {
		if (x != father[x]) {
			father[x] = find(father, father[x]); // 这个回溯时的压缩路径是精华
		}
		return father[x];
	}

	int Union(int[] father, int[] rank, int x, int y, int count) {
		x = find(father, x);
		y = find(father, y);
		if (x == y)
			return count;
		if (rank[x] > rank[y]) {
			father[y] = x;
		} else {
			if (rank[x] == rank[y]) {
				rank[y]++;
			}
			father[x] = y;
		}
		// 每次朋友圈合并,将朋友圈个数减1
		count--;
		return count;
	}
}

测试用例:{ { 1, 1, 0 }, { 1, 1, 0 }, { 0, 0, 1 } }

结果:2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值