链接
https://leetcode-cn.com/problems/number-of-provinces/
耗时
解题:24 min
题解:9 min
题意
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
思路
求图中连通块的数量,遍历每个点,从这个点开始bfs,并标记经过的点,计数遍历时没访问过的点的数量。
时间复杂度:
O
(
n
)
O(n)
O(n)
AC代码
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
vector<bool> vis(n, false);
int ans = 0;
for(int i = 0; i < n; ++i) {
if(vis[i]) continue;
vis[i] = true;
ans++;
queue<int> q;
q.push(i);
while(!q.empty()) {
int now = q.front();
q.pop();
for(int j = 0; j < n; ++j) {
if(isConnected[now][j]) {
if(vis[j]) continue;
vis[j] = true;
q.push(j);
}
}
}
}
return ans;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)