Cod sursa(job #1977703)

Utilizator LittleWhoFeraru Mihail LittleWho Data 5 mai 2017 21:38:56
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>

using namespace std;

vector<bool> visited(100000, false);
vector< vector<int> > nodes;
void DFS(int i)
{
    visited[i] = true;
    for (int j = 0; j < nodes[i].size(); j++) {
        if (!visited[nodes[i][j]]) {
            DFS(nodes[i][j]);
        }
    }
}

int main() {
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);

    int n, m;
    cin >> n >> m;

    nodes.reserve(n);
    for (int i = 0, x, y; i < m; i++) {
        cin >> x >> y;
        nodes[x - 1].push_back(y - 1);
        nodes[y - 1].push_back(x - 1);
    }

    for (int i = 0; i < n; i++) visited[i] = false;

    int solution = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            solution++;
            DFS(i);
        }
    }
    cout << solution << "\n";

    return 0;
}