Medium
LABNumber of Provinces
Given an adjacency matrix of connected cities, return the number of connected provinces.
EXAMPLES
Example 1
Input
{
"isConnected": [
[
1,
1,
0
],
[
1,
1,
0
],
[
0,
0,
1
]
]
}
Output
2FUNCTION SHAPE
isConnected: intMatrix→intSOLUTION NOTE
This is the same as the connected components question.
Reveal reference solution +
pythonREFERENCE
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
visited = set()
def dfs(city):
for neighbor in range(n):
if isConnected[city][neighbor] == 1 and neighbor not in visited:
visited.add(neighbor)
dfs(neighbor)
provinces = 0
for city in range(n):
if city not in visited:
visited.add(city)
dfs(city)
provinces += 1
return provincesTime
O(n^2)Space
O(n)