-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution547.java
43 lines (38 loc) · 1.04 KB
/
Solution547.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
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 朋友圈
* @date: 2018/08/15
*/
public class Solution547 {
public static void main(String[] args) {
Solution547 test = new Solution547();
int[][] M = new int[][]{
{1, 1, 0},
{1, 1, 0},
{0, 0, 1}};
System.out.println(test.findCircleNum(M));
}
public int findCircleNum(int[][] M) {
if (null == M || 0 >= M.length) {
return 0;
}
int circleNumber = 0;
boolean[] hasVisited = new boolean[M.length];
for (int i = 0; i < M.length; ++i) {
if (!hasVisited[i]) {
dfs(M, hasVisited, i);
++circleNumber;
}
}
return circleNumber;
}
private void dfs(int[][] M, boolean[] hasVisited, int i) {
hasVisited[i] = true;
for (int j = 0; j < M[i].length; ++j) {
if (1 == M[i][j] && !hasVisited[j]) {
dfs(M, hasVisited, j);
}
}
}
}