Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
0 3
| |
1 --- 2 4
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.
Example 2:
0 4
| |
1 --- 2 --- 3
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.
Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
思路:
1. 一直对图的问题有点畏惧,上次面试还遇到了这道题,磨磨蹭蹭到最后也没写出来。图的问题,简单的如这道题,就是遍历, DFS或BFS。DFS看是否有cycle回路,用recursive做;BFS可以找最短距离,用iterative做,比如queue。
2. 本题把所有点按照是否链接来分堆。就是如果距离有限,则分到一堆;距离无限,则是不同的堆。根距离有关,优先选BFS,用queue实现
int countComponents(int n, vector<pair<int, int> >& edges) {
vector<bool> visit(n,0);
int res=0;
queue<int> qq;
unordered_map<int,vector<int>> mm;
for(auto&edge:edges){
mm[edge.first].push_back(edge.second);
mm[edge.second].push_back(edge.first);
}
for(int i=0;i<n;i++){
if(visit[i]==1) continue;
visit[i]=1;
qq.push(i);
res++;
while(!qq.empty()){
int cur=qq.top();
qq.pop();
for(auto it=mm[cur].begin();it!=mm[cur].end();it++){
if(visit[*it]==0){
qq.push(*it);
visit[*it]=1;
}
}
}
}
return res;
}
3.本题还可以用DFS,不用queue。
int countComponents(int n, vector<pair<int, int> >& edges) {
vector<bool> visit(n,0);
int res=0;
unordered_map<int,vector<int>> mm;
for(auto&edge:edges){
mm[edge.first].push_back(edge.second);
mm[edge.second].push_back(edge.first);
}
for(int i=0;i<n;i++){
if(visit[i]==1) continue;
visit[i]=1;
res++;
dfs(mm,visit,i);
}
return res;
}
void dfs(unordered_map<int,vector<int>>&mm,vector<bool> &visit,int i){
if(visit[i]) return;
visit[i]=1;
for(auto&k:mm[i]){
dfs(mm,visit,k);
}
}