Implement a function int getComponentCount(vector<vector<int>> &G), where G is an adjacency list representation of the graph, and the return value is the count of components in the graph.
DFS
voidbfs(vector<vector<int>> &G,vector<bool> &visited,int start) {visited[start] =true; queue<int> q;q.push(start);while (q.size()) {int u =q.front();q.pop();for (int v :G[u]) {if (visited[v]) continue;visited[v] =true;q.push(v); } }}intgetComponentCount(vector<vector<int>> &G) {int ans =0; vector<bool>visited(G.size());for (int i =0; i <G.size(); ++i) {if (visited[i]) continue;++ans;bfs(G, visited, i); }return ans;}
BFS
voidbfs(vector<vector<int>> &G,vector<bool> &visited,int start) {visited[start] =true; queue<int> q;q.push(start);while (q.size()) {int u =q.front();q.pop();for (int v :G[u]) {if (visited[v]) continue;visited[v] =true;q.push(v); } }}intgetComponentCount(vector<vector<int>> &G) {int ans =0; vector<bool>visited(G.size());for (int i =0; i <G.size(); ++i) {if (visited[i]) continue;++ans;bfs(G, visited, i); }return ans;}
Union Find
classUnionFind { vector<int> id, rank;int cnt;public:UnionFind(int n) :cnt(n),id(n),rank(n,1) {for (int i =0; i < n; ++i) id[i] = i; }intfind(int a) {returnid[a] == a ? a : (id[a] =find(id[a])); }voidconnect(int a,int b) {int x =find(a), y =find(b);if (x == y) return;if (rank[x] <=rank[y]) {id[x] = y;if (rank[x] ==rank[y]) rank[y]++; } elseid[y] = x;--cnt; }intgetCount() { return cnt; }};intgetComponentCount(vector<vector<int>> &G) { UnionFind uf(G.size());for (int u =0; u <G.size(); ++u) {for (int v :G[u]) uf.connect(u, v); }returnuf.getCount();}