Number of Provinces
Number of Provinces is LeetCode 547 (Medium). There are n cities and an n × n matrix isConnected. isConnected[i][j] = 1 means cities i and j are directly connected; 0 means they are not.
A province is a group of cities joined directly or through other cities, with no link to any city outside the group. Return how many provinces there are.
- The matrix is symmetric, and every city is connected to itself (
isConnected[i][i] = 1). nis at most 200, so reading all n × n cells is cheap.
- 1 <= n <= 200
- n == isConnected.length
- n == isConnected[i].length
- isConnected[i][j] is 1 or 0.
- isConnected[i][i] == 1
- isConnected[i][j] == isConnected[j][i]
Intuition
A province is a connected component of the city graph, and isConnected is that graph's adjacency matrix. So the task is to count the separate pieces of the graph.
Pick a city no search has reached yet and run a depth-first search from it. The search follows every link it can, so it marks that city's whole province and nothing outside it. The next unmarked city must therefore belong to a different province.
So the number of searches you have to start is exactly the number of provinces.
Questions that ask how many separate groups exist, where links chain together (friends of friends, cities joined by roads, touching pixels), are counting connected components. Here the graph arrives as an adjacency matrix, so a city's neighbours are the columns holding 1 in its row. LeetCode 547 is the matrix version of Number of Connected Components in an Undirected Graph (LeetCode 323), which gives an edge list instead.
Approach
Before reading on: in the first example, which cities does one search from city 0 reach, and which city does the outer loop start the next search from? Aim for O(n²) time and O(n) extra space.
Two ways to solve it
Start a search from every city no search has reached; each start is one province.
- Time: one pass over the matrix.
- Extra state: a visited list and the recursion stack.
- Fits: a one-off count on a fixed matrix.
The shortest code for this problem.
Every link merges two cities' groups, and each merge of two different groups lowers the count by one.
- Time: effectively O(n²); α(n) is at most 4 here.
- Extra state: a parent and a size per city.
- Fits: links that arrive one at a time while the count must stay current.
The one to use when links arrive over time.
Both read every cell of the matrix, so they tie on speed, and the DFS is shorter. The steps, code and live demo follow the DFS; the Union-Find code is further down, after the demo.
Keep a visited list
Make visited = [False] * n. A city is marked the moment a search reaches it, so no city is explored or counted twice.
Search one whole province
dfs(u) marks u visited, then scans row u of the matrix. For every column v with isConnected[u][v] == 1 and v not yet visited, call dfs(v).
The column number is the neighbour; the 1 only says the link exists. Marking u before the scan means the 1 on the diagonal and the link back to the caller are both skipped.
Count the searches you start
Loop i from 0 to n - 1:
- if city
iis already visited, an earlier search covered its province, so skip it; - otherwise it starts a new province: add 1 to
provincesand calldfs(i).
Return provinces when the loop ends.
Code in Python, C++ and Java
Union-Find version
Start with every city in its own group, so count = n. For each pair i < j with a 1, find both group roots; if they differ, join the smaller group under the larger and subtract 1 from count. find halves the path as it climbs, which keeps the trees flat.
Common pitfalls
Looping over the row values instead of the columns
for v in isConnected[u]:
if not visited[v]:
dfs(v)for v in range(n):
if isConnected[u][v] == 1 and not visited[v]:
dfs(v)The row holds 0s and 1s, not city numbers. Looping over it visits cities 0 and 1 again and again and ignores the real neighbours. The neighbour is the column index; the value only says whether the link exists.
Marking a city visited after scanning its row
def dfs(u):
for v in range(n):
if isConnected[u][v] == 1 and not visited[v]:
dfs(v)
visited[u] = Truedef dfs(u):
visited[u] = True
for v in range(n):
...Every city has a 1 on the diagonal, and every link is stored both ways. If u is still unmarked while its row is scanned, the search calls dfs(u) again from itself or from its neighbour and never stops.
Complexity
Same count, three input shapes
These three problems all count connected groups. What differs is how you find a node's neighbours, and mixing them up is a common mistake, such as flood-filling isConnected as if it were a map.
| Problem | Input | A node is | Its neighbours |
|---|---|---|---|
| Number of Provinces (547) | n × n adjacency matrix | a city (row index) | columns with 1 in its row |
| Connected Components (323) | edge list | a vertex | adjacency list built from the edges |
| Number of Islands (200) | grid of land and water | a land cell | land cells up, down, left, right |
Number of Provinces FAQ
Can it be solved with BFS?
Yes. The DFS above can swap its recursion for a queue: push the start city, then repeatedly pop a city and push every unvisited city with a 1 in its row, marking each one when it is pushed. The count and the O(n²) time are the same, and there is no recursion depth to worry about.
Why is the time O(n²) even when there are only a few links?
Finding a city's neighbours means scanning its whole row, because the matrix has no list of only the 1s. Each of the n rows costs n, whatever the number of links. Converting to an adjacency list first still costs O(n²) to read the matrix.