Description
Submission
class Solution {
void dfs(vector<vector<int>>& next, int cur, vector<bool>& visited) {
if(visited[cur]) return;
visited[cur] = true;
for(auto i: next[cur]) {
dfs(next, i, visited);
}
}
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<vector<int>> next(n);
vector<bool> visited(n, false);
for(auto e: edges) {
next[e[0]].push_back(e[1]);
next[e[1]].push_back(e[0]);
}
int ret = 0;
for(int i = 0; i < n; ++i) {
if(!visited[i]) {
dfs(next, i, visited);
ret++;
}
}
return ret;
}
};