There are n cities. You get an n × n grid isConnected where isConnected[i][j] is 1 when city i and city j have a direct road between them and 0 when they do not. The grid is symmetric, and every city is linked to itself.
Cities that can reach each other through any chain of roads belong to the same province. Return how many provinces there are.
Example 1
Input: isConnected = [[1, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 1]]
Output: 2
Why: 0, 1, 2 are joined through 1; city 3 stands alone2 more examples and the constraints
Example 2
Input: isConnected = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] Output: 1 Why: every city has a road to every other
Example 3
Input: isConnected = [[1, 0], [0, 1]] Output: 2 Why: no roads, so each city is its own province
Constraints
- 1 ≤ n ≤ 200
- isConnected is n × n and holds only 0s and 1s
- isConnected[i][i] = 1, and isConnected[i][j] = isConnected[j][i]
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Union-FindO(n² · α(n))
- Depth-first searchO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 200 cities | Verdict |
|---|---|---|---|
| Union-Find | O(n² · α(n)) | Passes; good for streams of links | |
| Depth-first search | O(n²) | Best; simple and direct |
n = number of cities; α is the inverse Ackermann function, at most 4 in practice.
Edge cases to test
- One city. [[1]] is one province.
- No roads. The identity grid gives n provinces.
- Linked only through others. Cities 0 and 3 with no direct road can still share a province through a chain.
- Every road present. A grid full of 1s is one province.
Common mistakes
- Counting the 1s in the grid, or the cities with a road, instead of the groups.
- Forgetting to mark a city when it is pushed, so it is pushed again by another neighbour.
- Treating the diagonal 1s as roads to explore and looping on the same city.
How to talk through it
- 1Clarify. Is the grid always symmetric? Does a city with no roads count as its own province?
- 2Name the graph. Cities are nodes, 1s are edges, provinces are connected components.
- 3Pick a tool. DFS from each unvisited city, or Union-Find over the edges; both read the grid once.
- 4Code the search. Count a province only when the outer loop finds an unvisited city.
- 5Test out loud. Run one city, no roads, and a chain where two cities link only through a third.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?