forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindCircleNum.java
More file actions
31 lines (28 loc) · 865 Bytes
/
FindCircleNum.java
File metadata and controls
31 lines (28 loc) · 865 Bytes
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
package tree;
public class FindCircleNum {
public int findCircleNum(int[][] M){
boolean[] visited = new boolean[M.length];
int count = 0;
for (int i = 0; i < M.length; i++) {
if (!visited[i]){
dfs(M,visited,i);
count++;
}
}
return count;
}
private void dfs(int[][] M, boolean[] visited, int person) {
for (int other = 0;other < M.length;other++){
if (M[person][other] == 1 && !visited[other]){
visited[other] = true;
dfs(M,visited,other);
}
}
}
public static void main(String[] args) {
int[][] M ={{1,1,0},{1,1,0},{0,0,1}};
FindCircleNum findCircleNum = new FindCircleNum();
int r = findCircleNum.findCircleNum(M);
System.out.println(r);
}
}