当前位置:网站首页>剑指 Offer II 116. 省份数量-空间复杂度O(n),时间复杂度O(n)
剑指 Offer II 116. 省份数量-空间复杂度O(n),时间复杂度O(n)
2022-04-23 18:51:00 【Mr Gao】
剑指 Offer II 116. 省份数量
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
示例 1:
输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
输出:2
示例 2:
输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
输出:3
代如如下,简便递归法
void f2(int** isConnected, int n,int *r,int j){
int i;
r[j]=0;
for(i=0;i<n;i++){
if(isConnected[j][i]==1&&r[i]==1&&i!=j){
r[i]=0;
f2(isConnected,n,r,i);
}
}
}
void f(int** isConnected, int n,int *r,int *sum){
int i,j;
for(i=0;i<n;i++){
if(r[i]==1){
r[i]=0;
(*sum)++;
for(j=0;j<n;j++){
if(isConnected[i][j]==1&&r[j]==1&&i!=j){
f2(isConnected,n,r,j);
}
}
}
}
}
int findCircleNum(int** isConnected, int isConnectedSize, int* isConnectedColSize){
int n=isConnectedSize;
int *sum=(int *)malloc(sizeof(int));
int r[isConnectedSize];
int i;
for(i=0;i<n;i++){
r[i]=1;
}
*sum=0;
f(isConnected,n,r,sum);
return *sum;
}
版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43327597/article/details/124366819
边栏推荐
- Solutions such as unknown or garbled code or certificate problem prompt in Charles's mobile phone packet capture, actual measurement.
- ESP32 LVGL8. 1. Detailed migration tutorial of m5stack + lvgl + IDF (27)
- 【数学建模】—— 层次分析法(AHP)
- Sentinel服务熔断实战(sentinel整合ribbon+openFeign+fallback)
- Sentinel rule persistence into Nacos
- 程序员如何快速开发高质量的代码?
- Redis common interview questions
- Ucosiii transplantation and use, reference punctual atom
- 简化路径(力扣71)
- 解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本
猜你喜欢
mysql_linux版本的下載及安裝詳解
视频边框背景如何虚化,简单操作几步实现
根据快递单号查询物流查询更新量
Kettle paoding jieniu Chapter 17 text file output
ctfshow-web362(SSTI)
解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本
Halo open source project learning (VII): caching mechanism
WebView opens H5 video and displays gray background or black triangle button. Problem solved
【科普】CRC校验(一)什么是CRC校验?
实战业务优化方案总结---主目录---持续更新
随机推荐
Practice of Druid SQL and security in meituan review
Excel intercept text
Go language GUI framework Fyne Chinese garbled or not displayed
Sentinel service fusing practice (sentinel integration ribbon + openfeign + fallback)
ESP32 LVGL8. 1 - msgbox message box (msgbox 28)
从技术体系到商业洞察,中小研发团队架构实践之收尾篇
Machine learning theory (7): kernel function kernels -- a way to help SVM realize nonlinear decision boundary
os_ authent_ Prefix
Teach you to quickly rename folder names in a few simple steps
机器学习实战 -朴素贝叶斯
回路-通路
ESP32 LVGL8. 1 - label (style 14)
K210串口通信
迁移学习进阶
Simple use of navigation in jetpack
QT curve / oscilloscope customplot control
c#:泛型反射
How can programmers quickly develop high-quality code?
Use of kotlin collaboration in the project
Druid SQL和Security在美团点评的实践