Number of Provinces (LeetCode 547): Solution and Explanation
You have n cities and an n × n matrix telling you which pairs are directly connected. Cities connected directly or through a chain of other cities form a province, and you must count how many provinces there are.
Watch it run step by step
Try your own input and write the code →Intuition
A province is just a connected component of an undirected graph, so the question is how many components the graph has. The input is an adjacency matrix rather than an edge list, where isConnected[i][j] == 1 means cities i and j are linked, and the diagonal is always 1 because each city is connected to itself.
A brute force idea would be to compute, for every pair of cities, whether any path connects them, and then group cities that are mutually reachable. That is a transitive closure, which costs O(n³) with Floyd-Warshall style updates. It does far more work than needed because it answers every pairwise question when all you want is a count of groups.
The standard trick is to explore components one at a time. Walk through the cities in order. When you meet a city that has not been visited yet, it must belong to a province you have not counted, so add one to the count and run a DFS from it that marks every city reachable from it. Those cities will be skipped later, so each province is counted exactly once, at its first city.
With an adjacency matrix, finding a city's neighbors means scanning its whole row, which is why the total work is O(n²) no matter how many connections exist. That is fine here, since the input itself already has n² entries.
Approach: DFS over the adjacency matrix
- Create a
visitedlist of n False values and setprovinces = 0. - Define
dfs(city)that markscityvisited and loops over everyneighborfrom 0 to n - 1. - Inside the loop, recurse on any neighbor where
isConnected[city][neighbor] == 1and the neighbor is not visited. - Loop over each city in order; if it is not visited, call
dfs(city)and incrementprovinces. - Return
provinces.
Step-by-step example
isConnected = [[1,1,0],[1,1,0],[0,0,1]]
- City 0 is unvisited, so a DFS starts there and
provincesbecomes 1. - Scanning row 0 finds city 1 connected and unvisited, so the DFS visits city 1. Row 1 points back to city 0, which is already visited, and city 2 is not connected.
- City 1 is now visited, so the main loop skips it.
- City 2 is unvisited, so a new DFS starts and
provincesbecomes 2. Its row has no other connections. - The loop ends and the answer is 2: the province {0, 1} and the province {2}.
Code: Python, Java, C++
1class Solution:
2 def findCircleNum(self, isConnected: List[List[int]]) -> int:
3 n = len(isConnected)
4 visited = [False] * n
5 provinces = 0
6
7 def dfs(city):
8 visited[city] = True
9 for neighbor in range(n):
10 if isConnected[city][neighbor] == 1 and not visited[neighbor]:
11 dfs(neighbor)
12
13 for city in range(n):
14 if not visited[city]:
15 dfs(city)
16 provinces += 1
17
18 return provinces1class Solution {
2 public int findCircleNum(int[][] isConnected) {
3 int n = isConnected.length;
4 boolean[] visited = new boolean[n];
5 int provinces = 0;
6
7 for (int city = 0; city < n; city++) {
8 if (!visited[city]) {
9 dfs(isConnected, visited, city);
10 provinces++;
11 }
12 }
13
14 return provinces;
15 }
16
17 private void dfs(int[][] isConnected, boolean[] visited, int city) {
18 visited[city] = true;
19 for (int neighbor = 0; neighbor < isConnected.length; neighbor++) {
20 if (isConnected[city][neighbor] == 1 && !visited[neighbor]) {
21 dfs(isConnected, visited, neighbor);
22 }
23 }
24 }
25}1class Solution {
2public:
3 int findCircleNum(vector<vector<int>>& isConnected) {
4 int n = isConnected.size();
5 vector<bool> visited(n, false);
6 int provinces = 0;
7
8 for (int city = 0; city < n; city++) {
9 if (!visited[city]) {
10 dfs(isConnected, visited, city);
11 provinces++;
12 }
13 }
14
15 return provinces;
16 }
17
18private:
19 void dfs(vector<vector<int>>& isConnected, vector<bool>& visited, int city) {
20 visited[city] = true;
21 for (int neighbor = 0; neighbor < isConnected.size(); neighbor++) {
22 if (isConnected[city][neighbor] == 1 && !visited[neighbor]) {
23 dfs(isConnected, visited, neighbor);
24 }
25 }
26 }
27};Time and space complexity
O(n²)
Each city is visited once, and each visit scans its full row of n entries in the matrix.
O(n)
The visited list holds n flags and the recursion stack can be up to n deep when cities form a long chain.
Other approaches
Union-find (time O(n² × α(n)), space O(n))
Union every pair (i, j) with isConnected[i][j] == 1 and count how many cities remain their own root, or start with n and subtract one for every successful union. It avoids recursion and generalizes to streams of edges.
BFS (time O(n²), space O(n))
Same counting loop, but explore each province with a queue instead of recursion. Useful when n is large enough that deep recursion is a concern.
Common mistakes
- Counting provinces inside the DFS, or for every visited city, instead of once per DFS started from the main loop.
- Scanning only the upper triangle of the matrix in DFS; the walk needs every neighbor, so it must look at the whole row.
- Treating the input as an edge list and iterating
for a, b in isConnected, which misreads the matrix. - Marking a city visited after recursing into its neighbors instead of before, which can recurse back into it forever through the symmetric edge.
Frequently asked questions
Is number of provinces the same as counting connected components?
Yes. Each province is a connected component of the graph defined by the adjacency matrix, so the answer is the number of components.
Why is the time complexity O(n²)?
The input is an n × n matrix, and every DFS step scans an entire row to find neighbors. Each city's row is scanned once, giving n × n work in total.
DFS, BFS or union-find for number of provinces?
All three are accepted with similar complexity. DFS is the shortest to write, BFS avoids recursion depth issues, and union-find is handy when connections arrive one at a time.
Do I need to handle the diagonal?
No special handling is needed. The diagonal says each city connects to itself, and the visited check skips it naturally.