Menu
CoddyTech

Number of Provinces

There are n cities, numbered from 0 to n-1. You get an n × n matrix isConnected as a list of rows: isConnected[i][j] is 1 when a road links city i and city j directly, and 0 when it does not. Roads work both ways, so the matrix is symmetric, and every city counts as linked to itself.

A province is a group of cities that can all reach each other, directly or through other cities, with no road leading out of the group. Return the number of provinces.

Function

findCircleNum(isConnected: integer-2d-array) → integer
isConnectedinteger-2d-array
the n × n matrix, 1 where a road links two cities directly
Returnsinteger
the number of provinces

Constraints

  • 1 ≤ n ≤ 150, where n = isConnected.length
  • isConnected[i].length = n
  • isConnected[i][j] is 0 or 1
  • isConnected[i][i] = 1
  • isConnected[i][j] = isConnected[j][i]

Examples

Input
isConnected = [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]
Output
2
Explanation
City 0 has a road to city 3, and city 1 has a road to city 2. No road crosses between the two pairs, so there are 2 provinces.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Each road now opens on a given day. Can you find the first day on which all cities belong to a single province?

Reset code
def findCircleNum(isConnected):
    # Write code here
Test cases

Case 1

Case 2

Input

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

Expected

2