547. 省份数量
题目描述:
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
解题
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
1、准备
(1)节点间的relationship
在矩阵中,每个省由数字表示
所以relationship的最终体现为range(provinces)
provinces = len(isConnected)
(2)列表lst存放遍历结果
只计数
circles = 0
(3)集合set(去重)
每去过一个省便加入集合
visited = set()
2、递归
def dfs(i):
(1)节点不为空
(2)判断条件,是否输出
for j in range(provinces):
if isConnected[i][j] == 1 and j not in visited:
(3)依次取出relation中的下一个节点next_root,然后dfs(next_root)
visited.add(j)
dfs(j)
3、返回答案
for i in range(provinces):
if i not in visited:
dfs(i)
circles += 1
return circles
完整代码
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def dfs(i: int):
for j in range(provinces):
if isConnected[i][j] == 1 and j not in visited:
visited.add(j)
dfs(j)
provinces = len(isConnected)
visited = set()
circles = 0
for i in range(provinces):
if i not in visited:
dfs(i)
circles += 1
return circles