Number of Connected Components in an Undirected Graph (Leetcode 323)

基本的graph搜索题

1: DFS

class Solution {
public:
    int countComponents(int n, vector>& edges) {
        if(edges.empty()) return n;
        vector> graph(n, vector());
        int cnt = 0;
        for(auto it : edges){
            graph[it.first].push_back(it.second);
            graph[it.second].push_back(it.first);
        }
        vector visited(n, false);
        for(int i=0; i> &graph, vector &visited, int cur){
        if(visited[cur]) return;
        visited[cur] = true;
        for(int it : graph[cur]){
            if(!visited[it]){
                dfs(graph, visited, it);
            }
        }
    }
};
  1. BFS:
class Solution {
public:
    int countComponents(int n, vector>& edges) {
        if(edges.empty()) return n;
        vector> graph(n, vector());
        int cnt = 0;
        for(auto it : edges){
            graph[it.first].push_back(it.second);
            graph[it.second].push_back(it.first);
        }
        vector visited(n, false);
        queue q;
        for(int i=0; i
  1. 并查集,并查集直观找num of edges, 所以用n - num of edges就是结果
class Solution {
    
    unordered_map mp;
    int find_(int i){
        int parent = mp[i];
        while(parent != mp[parent]){
            parent = mp[parent];
        }
        int next;
        while(i != mp[i]){
            next = mp[i];
            mp[i] = parent;
            i = next;
        }
        return parent;
    }
    
    void union_(int p, int q){
        int parent_p = find_(p);
        int parent_q = find_(q);
        if(parent_p != parent_q){
            mp[parent_p] = parent_q;
        }
    }
    
public:
    int countComponents(int n, vector>& edges) {
        int cnt = 0;
        
        for(int i=0; i

你可能感兴趣的:(Number of Connected Components in an Undirected Graph (Leetcode 323))