547 Friend Circles

1. Question

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
1
Input:
2
3
[[1,1,0],
4
[1,1,0],
5
[0,0,1]]
6
7
Output: 2
8
9
Explanation:
10
The 0th and 1st students are direct friends, so they are in a friend circle.
11
12
The 2nd student himself is in a friend circle. So return 2.
Copied!
Example 2:
1
Input:
2
3
[[1,1,0],
4
[1,1,1],
5
[0,1,1]]
6
7
Output: 1
8
9
Explanation:
10
The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
11
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Copied!
Note:
  1. 1.
    N is in range [1,200].
  2. 2.
    M[i][i] = 1 for all students.
  3. 3.
    If M[i][j] = 1, then M[j][i] = 1.

2. Implementation

(1) DFS
1
class Solution {
2
public int findCircleNum(int[][] M) {
3
if (M == null || M.length == 0) {
4
return 0;
5
}
6
7
int n = M.length;
8
int count = 0;
9
boolean[] visited = new boolean[n];
10
for (int i = 0; i < n ; i++) {
11
if (!visited[i]) {
12
++count;
13
dfs(i, visited, M);
14
}
15
}
16
return count;
17
}
18
19
public void dfs(int i, boolean[] visited, int[][] M) {
20
visited[i] = true;
21
for (int j = 0; j < M.length; j++) {
22
if (M[i][j] == 1 && !visited[j]) {
23
dfs(j, visited, M);
24
}
25
}
26
}
27
}
Copied!
(2) Union Find
1
class Solution {
2
public int findCircleNum(int[][] M) {
3
int n = M.length;
4
UnionFind uf = new UnionFind(n);
5
6
for (int i = 0; i < n; i++) {
7
for (int j = 0; j < n; j++) {
8
if (i == j) continue;
9
if (M[i][j] == 1) {
10
uf.union(i, j);
11
}
12
}
13
}
14
return uf.count;
15
}
16
17
class UnionFind {
18
int[] sets;
19
int[] size;
20
int count;
21
22
public UnionFind(int n) {
23
sets = new int[n];
24
size = new int[n];
25
count = n;
26
27
for (int i = 0; i < n; i++) {
28
sets[i] = i;
29
size[i] = 1;
30
}
31
}
32
33
public int find(int node) {
34
while (node != sets[node]) {
35
node = sets[node];
36
}
37
return node;
38
}
39
40
public void union(int i, int j) {
41
int node1 = find(i);
42
int node2 = find(j);
43
44
if (node1 == node2) {
45
return;
46
}
47
48
if (size[node1] < size[node2]) {
49
sets[node1] = node2;
50
size[node2] += size[node1];
51
}
52
else {
53
sets[node2] = node1;
54
size[node1] += size[node2];
55
}
56
--count;
57
}
58
}
59
}
Copied!

3. Time & Space Complexity

DFS: 时间复杂度O(n^2), 空间复杂度O(n)
Union Find: 时间复杂度O(n^3), 遍历matrix需要O(n^2), 每call一次union()或者find()需要O(n)的时间,空间复杂度O(n)