Number of Provinces
MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.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.
[[1, 1, 0],
[1, 1, 0],
[0, 0, 1]] → 2 (cities 0 and 1 together, city 2 alone)
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]] → 3Constraints
1 <= n <= 200is_connected[i][i] == 1is_connected[i][j] == is_connected[j][i]