链接: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;
}
};