Number of Provinces

Medium Graph traversal DFS BFS

Problem

There are n cities, and isConnected[i][j] is 1 when city i is directly connected to city j. A province is a group of cities that are connected directly or indirectly. Return the number of provinces.

Original: LeetCode 547: Number of Provinces.

Examples

Example 1

Input`isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]`
Output`2`

Example 2

Input`isConnected = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]`
Output`3`

Constraints

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

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 547: Number of Provincesleetcode.com