-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09.NumberOfProvinces.java
60 lines (50 loc) · 1.43 KB
/
09.NumberOfProvinces.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
// DFS
class Solution {
public int findCircleNum(int[][] isConnected) {
int provinces = 0;
int V = isConnected.length;
boolean[] visited = new boolean[V];
for (int u = 0; u < V; u++) {
if (!visited[u]) {
provinces++;
dfs(isConnected, u, visited);
}
}
return provinces;
}
private void dfs(int[][] isConnected, int u, boolean[] visited) {
visited[u] = true;
for (int v = 0; v < isConnected[u].length; v++) {
if (isConnected[u][v] == 1 && !visited[v]) {
dfs(isConnected, v, visited);
}
}
}
}
// BFS
/*
class Solution {
public int findCircleNum(int[][] isConnected) {
int provinces= 0;
int V = isConnected[0].length;
boolean[] visited = new boolean[V];
Queue<Integer> que = new LinkedList<>();
for(int u =0;u < V;u++){
if(!visited[u]){
provinces++;
que.offer(u);
while(!que.isEmpty()){
int node = que.poll();
visited[node] = true;
for(int v=0; v<V ; v++){
if(isConnected[node][v] == 1 && !visited[v]){
que.offer(v);
}
}
}
}
}
return provinces;
}
}
*/