-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnected_component.cpp
More file actions
79 lines (67 loc) · 1.7 KB
/
connected_component.cpp
File metadata and controls
79 lines (67 loc) · 1.7 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <numeric>
#include <stack>
#include <unordered_map>
#include <vector>
using namespace std;
void dfs(const vector<vector<int>> &g, int s, vector<int> &visited,
unordered_map<int, vector<int>> &component, int c) {
// vector<bool> visited(g.size(), false);
stack<int> st;
st.push(s);
while (!st.empty()) {
int top = st.top();
st.pop();
visited[top] = true;
component[c].push_back(top);
// cout << top << ' ';
for (auto child : g[top]) {
if (!visited[child]) {
visited[child] = true;
st.push(child);
}
}
}
}
int dfs(const vector<vector<int>> &g) {
int components = 0;
unordered_map<int, vector<int>> component(g.size());
vector<int> visited(g.size(), false);
for (auto i = 0; i < g.size(); ++i) {
if (!visited[i]) {
visited[i] = true;
dfs(g, i, visited, component, components);
++components;
}
}
cout << '\n';
for (const auto &p : component) {
cout << p.first << ": ";
for (auto e : p.second) {
cout << e << " ";
}
cout << '\n';
}
return component.size();
}
int main() {
cout << "is_undirected: ";
char is_undirected = 'N';
cin >> is_undirected;
int n, m;
cin >> n >> m;
// g.size = n+1 if node start from 1, component returned from dfs =
// actual_component+1 (because zero is treated as seperate component) g.size =
// n if node start from 0
vector<vector<int>> g(n + 1);
for (int i = 1; i <= m; ++i) {
int v, u;
cin >> v >> u;
g[v].push_back(u);
if (is_undirected == 'Y' || is_undirected == 'y')
g[u].push_back(v);
}
auto components = dfs(g);
cout << '\n' << "Components: " << components << '\n';
return 0;
}