Skip to content

Commit 36b6460

Browse files
committed
547. Number of Provinces
1 parent 3c42fab commit 36b6460

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ The project is divided into two parts: `structure` and `solution`.
129129
| No. | Title | Difficulty | Solution | Idea |
130130
| ---- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | ---------- |
131131
| 329 | [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | Hard | [LongestIncreasingPathInAMatrix.java](src/leetcode/solution/DFS/LongestIncreasingPathInAMatrix.java) | DFS + Memo |
132+
| 547 | [Number of Provinces](https://leetcode.com/problems/number-of-provinces/) | Medium | [NumberOfProvinces.java](src/leetcode/solution/DFS/NumberOfProvinces.java) | DFS |
132133
| 802 | [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | Hard | [LongestIncreasingPathInAMatrix.java](src/leetcode/solution/DFS/LongestIncreasingPathInAMatrix.java) | DFS + Memo |
133134
| 2267 | [Check if There Is a Valid Parentheses String Path](https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/) | Medium | [FindEventualSafeStates.java](src/leetcode/solution/DFS/FindEventualSafeStates.java) | DFS |
134135

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package leetcode.solution.DFS;
2+
3+
/**
4+
* 547. Number of Provinces
5+
*/
6+
public class NumberOfProvinces {
7+
8+
public static void main(String[] args) {
9+
int[][] grid = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
10+
NumberOfProvinces numberOfProvinces = new NumberOfProvinces();
11+
int ans = numberOfProvinces.findCircleNum(grid);
12+
System.out.println(ans);
13+
// 2
14+
}
15+
16+
int[][] isConnected;
17+
18+
int[] visited;
19+
20+
int n;
21+
22+
public int findCircleNum(int[][] isConnected) {
23+
this.n = isConnected.length;
24+
this.isConnected = isConnected;
25+
this.visited = new int[n];
26+
27+
int count = 0;
28+
for (int i = 0; i < n; i++) {
29+
if (visited[i] == 1) {
30+
continue;
31+
}
32+
dfs(i);
33+
count++;
34+
}
35+
36+
return count;
37+
38+
}
39+
40+
private void dfs(int city) {
41+
visited[city] = 1;
42+
43+
for (int i = 0; i < n; i++) {
44+
if (city == i) {
45+
continue;
46+
}
47+
48+
if (isConnected[city][i] == 0) {
49+
continue;
50+
}
51+
52+
if (visited[i] == 1) {
53+
continue;
54+
}
55+
56+
dfs(i);
57+
}
58+
59+
}
60+
}

0 commit comments

Comments
 (0)