Leetcode 547 解析: Number of Provinces (Python)

该博客讨论了LeetCode的547题,即找出所有省份的数量。题目涉及城市间直接或间接的连接关系,一个省份是所有可以直接或间接连接的城市的集合。博主提出了使用深度优先搜索(DFS)的方法来解决,通过建立visited集合,遍历并递归地查找所有连通的城市,每找到一个连通的城市链,计数器加一。文章包含了详细的DFS实现代码和问题解析。
摘要由CSDN通过智能技术生成

题目描述

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

LC#547
Constraints:

1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] is 1 or 0.
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]

题目分析

这道省份的题目就是以前的朋友圈问题。

如果城市a能去到城市b, 他们之间就是直接连接的城市;如果城市b还能去到城市c,那么城市a和城市c之间就是间接连接的城市

一个省就是所有能互相连通的城市的集合。

现在我们有一个n乘n的矩阵 isConnected[i][j] == 1 代表着 i 城市和 j 城市之间是直接连接的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值