summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/01-decomposition/02-connected_components/connected_components.cpp
blob: d6b148b00daf9a2d460e5febb081b98269e47878 (plain)
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
#include <iostream>
#include <vector>
#include <stack>

using std::vector;
using std::stack;
using std::pair;

int number_of_components(vector<vector<int> > &adj)
{
    vector<bool> visited(adj.size());
    stack<int> st;

    int cc = 0;
    for (int j = 0; j < adj.size(); j++) {
        if (visited[j])
            continue;
        cc += 1;
        st.push(j);
        while(!st.empty()) {
            int v = st.top();
            st.pop();
            visited[v] = true;
            int s = adj[v].size();
            for (int i = 0; i < s; i++) {
                int w = adj[v][i];
                if (!visited[w])
                    st.push(w);
            }
        }
    }

    return cc;
}

int main() {
  size_t n, m;
  std::cin >> n >> m;
  vector<vector<int> > adj(n, vector<int>());
  for (size_t i = 0; i < m; i++) {
    int x, y;
    std::cin >> x >> y;
    adj[x - 1].push_back(y - 1);
    adj[y - 1].push_back(x - 1);
  }
  std::cout << number_of_components(adj) << '\n';
}