Home 无向图中的所有连通分量
Post
Cancel

无向图中的所有连通分量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <map>
#include <list>
#include <vector>

using namespace std;

int merge(vector<int> parent, int x)
{
    if (parent[x] == x)
    {
        return x;
    }
    return merge(parent, parent[x]);
}

vector<vector<int>> connected_components(int n, vector<pair<int, int>> &edges)
{
    vector<int> parent;
    vector<vector<int>> result;
    for (int i = 0; i < n; i++)
    {
        parent.push_back(i);
    }
    for (const auto &x : edges)
    {
        parent[merge(parent, x.first)] = merge(parent, x.second);
    }
    for (int i = 0; i < n; i++)
    {
        parent[i] = merge(parent, parent[i]);
    }
    map<int, list<int>> m;
    for (int i = 0; i < n; i++)
    {
        m[parent[i]].push_back(i);
    }
    for (auto it = m.begin(); it != m.end(); it++)
    {
        list<int> l = it->second;
        vector<int> temp;
        for (const auto &x : l)
        {
            temp.push_back(x);
        }
        result.push_back(temp);
    }
    return result;
}
This post is licensed under CC BY 4.0 by the author.