Skip to main content
Back to problems
Leetcode
Medium
Graphs
Union Find
Graph Connectivity
Google
Number Of Provinces

Count how many connected components exist in an undirected graph described by an adjacency matrix.

Acceptance 100%
Problem Statement

You are given an n×nn \times n adjacency matrix isConnected for an undirected graph with n cities. If isConnected[i][j] = 1, city i and city j are directly connected; otherwise they are not.

A province is a group of cities that are directly or indirectly connected, and no city outside the group is connected to them.

Return the number of provinces in the graph.

You may solve this using graph traversal or a disjoint set approach.

Input Format

  • An integer nn represented implicitly by the size of isConnected.
  • A square n×nn \times n matrix isConnected where isConnected[i][j] is 0 or 1.
  • The matrix is symmetric and isConnected[i][i] = 1 for all valid i.

Output Format

  • Return a single integer: the number of connected components in the graph.

Constraints

  • 1n2001 \le n \le 200
  • isConnected.length == n
  • isConnected[i].length == n
  • isConnected[i][j] is either 0 or 1
  • isConnected[i][j] == isConnected[j][i]
  • isConnected[i][i] == 1
Examples
Sample cases returned by the problem API.

Example 1

Input

isConnected = [[1,1,0],[1,1,0],[0,0,1]]

Output

2

Explanation

Cities 0 and 1 form one connected component, and city 2 forms another. So there are 2 provinces.

Example 2

Input

isConnected = [[1,0,0],[0,1,0],[0,0,1]]

Output

3

Explanation

No city is connected to any other city, so each city is its own province.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.