Cod sursa(job #1977647)

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

using namespace std;

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

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

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

    vector<bool> visited(n, false);
    vector< vector<int> > nodes(n);

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

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

    return 0;
}