-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathFindCircles.java
63 lines (50 loc) · 1.56 KB
/
FindCircles.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package problems.leetcode;
/**
* https://leetcode.com/problems/friend-circles/
*/
public class FindCircles {
public static void main(String[] args) {
int[][] friends = {{1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 1, 1}};
int circles = findCircleNum(friends);
System.out.println(circles);
}
public static int findCircleNum(int[][] M) {
int circles = 0;
for (int student1 = 0; student1 < M.length; student1++) {
for (int student2 = 0; student2 < M.length; student2++) {
if (M[student1][student2] == 1) {
circles++;
M[student1][student2] = -circles;
M[student2][student2] = -circles;
depthFirstSearch(M, student2, -circles);
}
}
}
return circles;
}
private static void depthFirstSearch(int[][] M, int student1, int marker) {
for (int student2 = 0; student2 < M.length; student2++) {
if (M[student1][student2] == 1) {
M[student1][student2] = marker;
M[student2][student2] = marker;
depthFirstSearch(M, student2, marker);
}
}
}
/*
Input:
0 1 2
0[1,1,0],
1[1,1,0],
2[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
0-1
0 1 2 3
0 1,0,0,1
1 0,1,1,0
2 0,1,1,1
3 1,0,1,1
*/
}