🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

Number of Provinces medium

Description

There are n cities. Some of them are connected, while some are not. If city a is connected to city b, and city b is connected to city c, then city a is indirectly connected to city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n × n matrix isConnected where isConnected[i][j] = 1 if the ith and jth cities are directly connected, and 0 otherwise.

Return the total number of provinces.

Examples

> Case 1:
    isConnected = [[1,1,0],[1,1,0],[0,0,1]]
    Output: 2
    # {0, 1} and {2}.
 
> Case 2:
    isConnected = [[1,0,0],[0,1,0],[0,0,1]]
    Output: 3

Constraints

  • 1 <= n <= 200
  • n == isConnected.length == isConnected[i].length
  • isConnected[i][j] is 1 or 0.
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

State design

Pure component counting. For every off-diagonal 1, union the two indices. The final number of distinct roots is the answer — and the components counter we maintain in the DSU template gives it directly.

Only need to walk the upper triangle (since the matrix is symmetric) for a small constant-factor win.

Code

Analysis

  • Time: O(n² · α(n)) — scan the matrix once, near-constant per union.
  • Space: O(n) for the DSU arrays.

DFS solves this too, in the same complexity. DSU wins when you want the “components after each new edge” running count. For one-shot static counting, both are fine — pick the one you can write fastest.

Same skin

  • Number of Connected Components in an Undirected Graph — same idea, edge list instead of matrix.
  • Friend Circles — older name for this exact problem.
  • Number of Operations to Make Network Connected — components and spare edges, both via DSU.