首页 > 代码库 > [LeetCode] 547. Friend Circles
[LeetCode] 547. Friend Circles
https://leetcode.com/problems/friend-circles
public class Solution { int[] id; int[] weight; public int findCircleNum(int[][] M) { if (M == null || M.length == 0 || M[0].length == 0) { return 0; } initUnionFind(M.length); Set<Integer> set = new HashSet<>(); for (int i = 0; i < M.length; i++) { for (int j = 0; j < M[0].length; j++) { if (i == j) { continue; } if (M[i][j] == 1) { union(i, j); } } } for (int i = 0; i < id.length; i++) { int root = find(i); if (!set.contains(root)) { set.add(root); } } return set.size(); } private void initUnionFind(int n) { id = new int[n]; weight = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; weight[i] = 1; } } private void union(int i, int j) { int rootI = find(i); int rootJ = find(j); if (rootI == rootJ) { return; } if (weight[rootI] > weight[rootJ]) { id[rootJ] = rootI; weight[rootI] += weight[rootJ]; } else { id[rootI] = rootJ; weight[rootJ] += weight[rootI]; } } private int find(int i) { while (i != id[i]) { return find(id[i]); } return i; } }
[LeetCode] 547. Friend Circles
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。