#547

Number of Provinces

Medium Connected components (adjacency matrix)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

isConnected[i][j] = 1 means cities i and j are directly connected. A province is a group of connected cities. Count provinces.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many connected groups of cities?

Why this works: the input is an adjacency matrix; count how many DFS runs you need to visit every city.

Example: [[1,1,0],[1,1,0],[0,0,1]]

DFS from 0 visits 0, 1DFS from 2 visits 2 → 2 provinces

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Treating the matrix as a grid and running "islands" over its cells — the cells are edges, not nodes.

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(n).
Topic: Graphs
🎬 Episodes 74–85: video coming soon