Cod sursa(job #1464112)

Utilizator dex4Darjan Catalin dex4 Data 22 iulie 2015 13:06:24
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#define nmax 10005

using namespace std;

vector<int> G[nmax];
int viz[nmax], n, m, x, y, comps;

void build(){
    ifstream f("dfs.in");
    f >> n >> m;
    for(int i=1; i<=m; i++){
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void dfs(int x){
    int s;
    s = G[x].size();
    viz[x] = 1;
    for(int i=0; i<s; i++){
        int y = G[x][i];
        if(!viz[y])
            dfs(y);
    }

}

int main()
{
    ofstream g("dfs.out");
    build();
    for(int i=1; i<=n; i++){
        if(viz[i] == 0){
            dfs(i);
            comps++;
        }
    }
    cout << comps;
    return 0;
}