Skip to main content

Number of Connected Components in an Undirected Graph

描述​

TODO

分析​

TODO

代码​

深搜​

# Empty stub since input only contains a comment
# TODO

并查集​

class DSU {
// Plese copy from https://algorithm-essentials.soulmachine.me/graph/ufs/#union-by-rank
};

// Number of Connected Components in an Undirected Graph
// Time complexity: O(E*log*V)
// Space complexity: O(V)
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
const int E = edges.size();
DSU dsu(n);

int components = n;
for (int i = 0; i < E; i++) {
components -= dsu.merge(edges[i][0], edges[i][1]);
}
return components;
}
};

相关题目​