LeetCode #547 Medium

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).
  • n is at most 200, so reading all n × n cells is cheap.
Constraints
  • 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]
graphdfsunion-find
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

Count the searches you start

Loop i from 0 to n - 1:

  • if city i is already visited, an earlier search covered its province, so skip it;
  • otherwise it starts a new province: add 1 to provinces and call dfs(i).

Return provinces when the loop ends.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findCircleNum(self, isConnected: List[List[int]]) -> int:
▶3 n = len(isConnected)
▶4 visited = [False] * n
▶5 
▶6 def dfs(u):
▶7 visited[u] = True
▶8 for v in range(n):
▶9 if isConnected[u][v] == 1 and not visited[v]:
▶10 dfs(v)
▶11 
▶12 provinces = 0
▶13 for i in range(n):
▶14 if not visited[i]:
▶15 provinces += 1
▶16 dfs(i)
▶17 return provinces
isConnected01234011000111010200101301010400101cities01234call stackemptyno city visited yet
provinces0searches started
visited0 / 5cities
Every city starts unvisited and the count is 0. Row r of the matrix lists who city r is linked to: a 1 in column c means a direct link to city c. The graph on the right draws the same links.
isConnected01234011000111010200101301010400101cities01234call stackemptycity 0 unvisited → provinces = 1
i0not visited
provinces1searches started
visited0 / 5cities
No search has reached city 0, so it cannot be linked to any province found so far. It starts a new province: add 1, then search from it to mark everything it can reach.
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)visit city 0
u0start of a search
provinces1searches started
visited1 / 5cities
Mark city 0 visited right away, before its row is read. Now scan row 0 for linked cities the search has not reached yet.
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)dfs(1)visit city 1
u1reached from 0
provinces1searches started
visited2 / 5cities
Row 0 has a 1 in column 1 and city 1 is not visited, so the search moves to it and marks it. Now scan row 1 for linked cities the search has not reached yet.
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)dfs(1)dfs(3)visit city 3
u3reached from 1
provinces1searches started
visited3 / 5cities
Row 1 has a 1 in column 3 and city 3 is not visited, so the search moves to it and marks it. Now scan row 3 for linked cities the search has not reached yet.
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)dfs(1)dfs(3)row 3 done, return
u3row fully scanned
provinces1searches started
visited3 / 5cities
Row 3 is finished. The 1 on the diagonal is city 3 itself, and 1 was already visited when the scan reached it (dashed), so nothing new is left. dfs(3) returns to dfs(1).
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)dfs(1)row 1 done, return
u1row fully scanned
provinces1searches started
visited3 / 5cities
Row 1 is finished. Column 3 (green) already led the search onward, and that search has returned. The 1 on the diagonal is city 1 itself, and 0 was already visited when the scan reached it (dashed), so nothing new is left. dfs(1) returns to dfs(0).
isConnected01234011000111010200101301010400101cities01234call stackdfs(0)row 0 done, return
u0row fully scanned
provinces1searches started
visited3 / 5cities
Row 0 is finished. Column 1 (green) already led the search onward, and that search has returned. The 1 on the diagonal is city 0 itself (dashed), so nothing new is left. dfs(0) returns to the outer loop.
isConnected01234011000111010200101301010400101citiesprovince 101234call stackemptycity 1 visited, skip
i1already visited
provinces1searches started
visited3 / 5cities
City 1 is already marked: an earlier search reached it, so it belongs to a province that has been counted. Starting here again would count that province twice.
isConnected01234011000111010200101301010400101citiesprovince 101234call stackemptycity 2 unvisited → provinces = 2
i2not visited
provinces2searches started
visited3 / 5cities
No search has reached city 2, so it cannot be linked to any province found so far. It starts a new province: add 1, then search from it to mark everything it can reach.
isConnected01234011000111010200101301010400101citiesprovince 101234call stackdfs(2)visit city 2
u2start of a search
provinces2searches started
visited4 / 5cities
Mark city 2 visited right away, before its row is read. Now scan row 2 for linked cities the search has not reached yet.
isConnected01234011000111010200101301010400101citiesprovince 101234call stackdfs(2)dfs(4)visit city 4
u4reached from 2
provinces2searches started
visited5 / 5cities
Row 2 has a 1 in column 4 and city 4 is not visited, so the search moves to it and marks it. Now scan row 4 for linked cities the search has not reached yet.
isConnected01234011000111010200101301010400101citiesprovince 101234call stackdfs(2)dfs(4)row 4 done, return
u4row fully scanned
provinces2searches started
visited5 / 5cities
Row 4 is finished. The 1 on the diagonal is city 4 itself, and 2 was already visited when the scan reached it (dashed), so nothing new is left. dfs(4) returns to dfs(2).
isConnected01234011000111010200101301010400101citiesprovince 101234call stackdfs(2)row 2 done, return
u2row fully scanned
provinces2searches started
visited5 / 5cities
Row 2 is finished. Column 4 (green) already led the search onward, and that search has returned. The 1 on the diagonal is city 2 itself (dashed), so nothing new is left. dfs(2) returns to the outer loop.
isConnected01234011000111010200101301010400101citiesprovince 1province 201234call stackemptycity 3 visited, skip
i3already visited
provinces2searches started
visited5 / 5cities
City 3 is already marked: an earlier search reached it, so it belongs to a province that has been counted. Starting here again would count that province twice.
isConnected01234011000111010200101301010400101citiesprovince 1province 201234call stackemptycity 4 visited, skip
i4already visited
provinces2searches started
visited5 / 5cities
City 4 is already marked: an earlier search reached it, so it belongs to a province that has been counted. Starting here again would count that province twice.
isConnected01234011000111010200101301010400101citiesprovince 1province 201234call stackemptyreturn 2
answer2provinces
provinces2searches started
visited5 / 5cities
Answer 2. The outer loop started 2 searches, and each one marked exactly one whole province. Every row was scanned once, so the work was 5 × 5 cells.
05

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.

▶1class Solution:
▶2 def findCircleNum(self, isConnected: List[List[int]]) -> int:
▶3 n = len(isConnected)
▶4 parent = list(range(n))
▶5 size = [1] * n
▶6 
▶7 def find(x):
▶8 while parent[x] != x:
▶9 parent[x] = parent[parent[x]]
▶10 x = parent[x]
▶11 return x
▶12 
▶13 count = n
▶14 for i in range(n):
▶15 for j in range(i + 1, n):
▶16 if isConnected[i][j] == 1:
▶17 a, b = find(i), find(j)
▶18 if a != b:
▶19 if size[a] < size[b]:
▶20 a, b = b, a
▶21 parent[b] = a
▶22 size[a] += size[b]
▶23 count -= 1
▶24 return count
06

Common pitfalls

Looping over the row values instead of the columns

✗ Wrong
for v in isConnected[u]:
    if not visited[v]:
        dfs(v)
✓ Right
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

✗ Wrong
def dfs(u):
    for v in range(n):
        if isConnected[u][v] == 1 and not visited[v]:
            dfs(v)
    visited[u] = True
✓ Right
def 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.

07

Complexity

Time
O(n²)
Space
O(n)
Each city's row is scanned once, so the DFS reads all n² cells, which is also the cost of just reading the input. The visited list and the recursion stack are O(n). In Python, the recursion is at most 200 deep, well under the default limit of 1000.
08

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.

ProblemInputA node isIts neighbours
Number of Provinces (547)n × n adjacency matrixa city (row index)columns with 1 in its row
Connected Components (323)edge lista vertexadjacency list built from the edges
Number of Islands (200)grid of land and watera land cellland cells up, down, left, right
09

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.