链接:https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/
用数组记录下连通关系(注意是双向的),然后用dfs检查共有几个连通图,答案即为连通图的数量减1.
C++代码:
class Solution {
vector<vector<int>> edges;
vector<bool> used;
public:
int makeConnected(int n, vector<vector<int>>& connections) {
if(n>connections.size()+1)
return -1;
edges.resize(n);
for (auto&& c: connections) {
edges[c[0]].push_back(c[1]);
edges[c[1]].push_back(c[0]);
}
used.resize(n);
int part = 0;
for (int i = 0; i < n; ++i) {
if (!used[i]) {
++part;
dfs(i);
}
}
return part - 1;
}
void dfs(int index)
{
used[index] = 1;
for(int i:edges[index])
if(used[i]!=1 )
dfs(i);
return;
}
};
本文探讨了如何解决网络连通问题,通过使用深度优先搜索(DFS)算法,记录连通关系并计算连通图数量,最终确定所需操作次数使网络完全连通。代码示例采用C++实现。
&spm=1001.2101.3001.5002&articleId=108020748&d=1&t=3&u=eba11d9b470b464394ef25d4cf9c3df1)
1472

被折叠的 条评论
为什么被折叠?



