-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFriendCircles.java
More file actions
47 lines (42 loc) · 1.02 KB
/
Copy pathFriendCircles.java
File metadata and controls
47 lines (42 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.algorithm.playground.leetcode.problems.lc500.lc540.lc547;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* https://leetcode.com/problems/friend-circles/description/
*/
public class FriendCircles {
class Solution {
public int findCircleNum(int[][] M) {
if (M.length == 0) {
return 0;
}
int[] parents = new int[M.length];
Arrays.fill(parents, -1);
for (int r = 0; r < M.length; r++) {
for (int c = 0; c < M.length; c++) {
if (M[r][c] == 1) {
int p1 = find(parents, r);
int p2 = find(parents, c);
if (p1 != p2) {
parents[p1] = p2;
}
}
}
}
Set<Integer> values = new HashSet<>();
for (int i = 0; i < parents.length; i++) {
values.add(find(parents, i));
}
return values.size();
}
private int find(int[] parents, int key) {
if (parents[key] == -1) {
return parents[key] = key;
} else if (parents[key] == key) {
return key;
}
return parents[key] = find(parents, parents[key]);
}
}
}