File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # leetcode 547
2+ class Solution {
3+ static int[] parent;
4+ static int count;
5+
6+ public static int findCircleNum(int[][] friends) {
7+ if (friends == null || friends.length == 0 || friends[0].length == 0) {
8+ return 0;
9+ }
10+ parent = new int[friends.length];
11+ count = friends.length;
12+ for (int i = 0; i < friends.length; i++) {
13+ parent[i] = i;
14+ }
15+ for (int i = 0; i < friends.length; i++) {
16+ for (int j = i+1; j < friends.length; j++) {
17+ if (friends[i][j] == 1) {
18+ union(i, j);
19+ }
20+ }
21+ }
22+ return count;
23+ }
24+
25+ public static void union(int p, int q) {
26+ int rootP = find(p);
27+ int rootQ = find(q);
28+ if (rootP == rootQ) {
29+ return;
30+ }
31+ parent[rootQ] = rootP;
32+ count--;
33+ }
34+
35+ public static int find(int e) {
36+ while (parent[e] != e) {
37+ parent[e] = parent[parent[e]];//让子节点直接连接父节点
38+ e = parent[e];
39+ }
40+ return e;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments