547. 省份数量(深度优先搜索)(傻瓜教程)(python)(LC)

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

深度优先搜索的框架

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Grayson Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值