LeetCode 323. Number of Connected Components in an Undirected Graph

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);    
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值