Skip to content
Decoder

Number of Provinces

Medium

Problem

There are n cities. You get an n x n matrix is_connected where is_connected[i][j] == 1 means cities i and j have a direct road, and 0 means they do not. Roads go both ways, and if a connects to b and b connects to c, then a and c are in the same group. A province is a group of cities that are directly or indirectly connected, with no other city. Return the number of provinces.

Example 1

[[1, 1, 0],

Example 2

 [1, 1, 0],

Example 3

Input
[0, 0, 1]]
Output
2
Why
cities 0 and 1 together, city 2 alone

Example 4

[[1, 0, 0],

Example 5

 [0, 1, 0],

Example 6

Input
[0, 0, 1]]
Output
3

Constraints

  • 1 <= n <= 200
  • is_connected[i][i] == 1
  • is_connected[i][j] == is_connected[j][i]

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.