Graphs Traversing a graph
452. Number of Provinces
There are n cities, numbered from 0 to n - 1. You are given an n × n matrix isConnected. The
value isConnected[i][j] is 1 when cities i and j are directly connected, and 0 when they are not.
A connection works both ways, so isConnected[i][j] equals isConnected[j][i]. Every city counts as
connected to itself, so isConnected[i][i] is 1.
A province is a group of cities in which every city can reach every other one through a chain of direct connections, and that no connection joins to a city outside the group. A city with no connections is a province on its own.
Return the number of provinces.
Example 1
Input: isConnected = [[1, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 1]]
3Explanation: Cities 0, 3 and 5 form one province. Cities 0 and 5 are not directly connected, but both are connected to city 3. Cities 1 and 4 form the second province, and city 2 is the third.
Example 2
Input: isConnected = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
3Explanation: No two cities are connected, so each city is a province on its own.
Example 3
Input: isConnected = [[1, 0, 1, 0],
[0, 1, 1, 1],
[1, 1, 1, 0],
[0, 1, 0, 1]]
1Explanation: City 0 is connected to city 2, city 2 to city 1, and city 1 to city 3. So city 0 reaches city 3 through cities 2 and 1, and all four cities are one province.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
n == isConnected.length == isConnected[i].length1 ≤ n ≤ 1000isConnected[i][j]is 0 or 1.isConnected[i][i] == 1isConnected[i][j] == isConnected[j][i]
Clarifying questions
What you would ask an interviewer before writing any code.