You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*[138. Copy List with Random Pointer](https://github.com/Seanforfun/Algorithm-and-Leetcode/blob/master/leetcode/138.%20Copy%20List%20with%20Random%20Pointer.md)
624
+
*[200. Number of Islands](https://github.com/Seanforfun/Algorithm-and-Leetcode/blob/master/leetcode/200.%20Number%20of%20Islands.md)
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.
5
+
6
+
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.
7
+
8
+
```
9
+
Example 1:
10
+
Input:
11
+
[[1,1,0],
12
+
[1,1,0],
13
+
[0,0,1]]
14
+
Output: 2
15
+
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
16
+
The 2nd student himself is in a friend circle. So return 2.
17
+
Example 2:
18
+
Input:
19
+
[[1,1,0],
20
+
[1,1,1],
21
+
[0,1,1]]
22
+
Output: 1
23
+
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
24
+
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
25
+
```
26
+
27
+
Note:
28
+
* N is in range [1,200].
29
+
* M[i][i] = 1 for all students.
30
+
* If M[i][j] = 1, then M[j][i] = 1.
31
+
32
+
### Solution:
33
+
* Method 1:Union find
34
+
```Java
35
+
classSolution {
36
+
privateint[] uf;
37
+
privateint num;
38
+
publicintfindCircleNum(int[][] M) {
39
+
if(M==null||M.length ==0) return0;
40
+
this.num =M.length;
41
+
uf =newint[num];
42
+
for(int i =0; i < num; i++) uf[i] = i;
43
+
for(int i =0; i < num; i++){
44
+
for(int j = i +1; j < num; j++){
45
+
if(M[i][j] ==1){ //means student i and j are friends
46
+
union(i, j);
47
+
}
48
+
}
49
+
}
50
+
int res =0;
51
+
for(int i =0; i < uf.length; i++){
52
+
if(uf[i] == i)
53
+
res++;
54
+
}
55
+
return res;
56
+
}
57
+
privatevoidunion(inti, intj){
58
+
int p = find(i);
59
+
int q = find(j);
60
+
if(p != q){
61
+
uf[p] = q;
62
+
}
63
+
}
64
+
privateintfind(inti){
65
+
if(uf[i] != i){
66
+
uf[i] = find(uf[i]);
67
+
}
68
+
return uf[i];
69
+
}
70
+
}
71
+
```
72
+
73
+
* Method 2: DFS
74
+
* Once we get a not visited student, we set all its friends(including himself) as visited.
0 commit comments