Skip to content

Commit eb6fc4c

Browse files
authored
Create sourcema.md
1 parent 318c535 commit eb6fc4c

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

2019.01.08-leetcode547/sourcema.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)