Cod sursa(job #1559596)

Utilizator DanielRusuDaniel Rusu DanielRusu Data 31 decembrie 2015 11:18:54
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 kb
#include <cstdio>
#include <vector>
#include <iostream>

using namespace std;

#define DIM 100005

vector <vector <int> > Graph;
int visited[DIM], N, M, x, y;

void DFS(int nod);

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

    scanf("%d %d\n", &N, &M);

    Graph.resize(N + 1);

    for(int i = 1; i <= M; ++i) {
        scanf("%d %d\n", &x, &y);

        Graph[x].push_back(y);
        Graph[y].push_back(x);
    }

    int answer = 0;

    for(int i = 1; i <= N; ++i) {
        if(!visited[i]) {
            DFS(i);
            ++answer;
        }
    }

    cout << answer << '\n';
}

void DFS(int nod) {
    visited[nod] = 1;

    for(auto x: Graph[nod]) {
        if(!visited[x]) {
            DFS(x);
        }
    }
}