Number of provinces
Standard · Write code · about 10 min
There are n cities. isConnected[i][j] is 1 when cities i and j are directly linked and 0 otherwise. A province is a group of cities linked directly or through other cities. Return the number of provinces.
Example 1
Input:
[[[1,1,0],[1,1,0],[0,0,1]]]
Output:
2
Cities 0 and 1 are linked; city 2 is alone.
Example 2
Input:
[[[1,0,0],[0,1,0],[0,0,1]]]
Output:
3
Constraints
- 1 ≤ n ≤ 200
- isConnected[i][i] = 1 and isConnected[i][j] = isConnected[j][i]
Learn the idea first: Union-find applications: connectivity, grouping, redundant edges, a visual lesson.
More Union-find applications: connectivity, grouping, redundant edges problems
- Merge or cycle? Warm-up
- Redundant connection Standard
- Accounts merge Standard