Tensorum
LeetCode 547 · Graph Fundamentals / DFS + DSU

Number of Provinces

LeetCode 547 · Medium · solution, intuition & step-by-step walkthrough

Count connected components with DFS.

MediumDepth-First SearchBreadth-First SearchUnion-FindGraph Theory
5 msruntime · beats 62%
21.6 MBmemory · beats 12%
1approach
16accepted runs · last 17 Sept 2026

This is how I solved Number of Provinces (LeetCode 547), a medium problem from the Graph Fundamentals / DFS + DSU pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Cities and direct connections form a graph given as an adjacency matrix. Each DFS from an unvisited city marks one connected component — one province.

Approach

  1. 1

    For each unvisited city, DFS and count a province.

  2. 2

    DFS visits every city with isConnected[u][v] == 1.

How I solved it

DFS on adjacency matrixPythonO(n²) time
class Solution:
    def findCircleNum(self, isConnected: List[List[int]]) -> int:
        n = len(isConnected)
        visited = set()
        def dfs(u):
            visited.add(u)
            for v in range(n):
                if isConnected[u][v]==1 and v not in visited:
                    dfs(v)
        components=0
        for u in range(n):
            if u not in visited:
                dfs(u)
                components+=1
        return components
            
Loading the step-through…

Number of Provinces — FAQ

What is the intuition behind Number of Provinces?

Cities and direct connections form a graph given as an adjacency matrix. Each DFS from an unvisited city marks one connected component — one province.

How do you solve Number of Provinces (LeetCode 547)?

1. For each unvisited city, DFS and count a province. 2. DFS visits every city with isConnected[u][v] == 1.

What is the time and space complexity of Number of Provinces?

Time: O(n²). Space: O(n). (Accepted approach: DFS on adjacency matrix.)

What are common mistakes in Number of Provinces?

The matrix is symmetric — no need to look at both triangles specially.