Cod sursa(job #1370278)

Utilizator FapFapAdriana FapFap Data 3 martie 2015 13:43:48
Problema Parcurgere DFS - componente conexe Scor 75
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#define nmax 50005
using namespace std;

ifstream fin ("dfs.in");
ofstream fout ("dfs.out");

int nr_of_nodes, nr_of_edges;
bool seen[nmax];
vector<int> v[nmax];

void dfs(int x){
    seen[x]= true; // marc current as seen
    for(int i=0; i<v[x].size(); i++) // iterate current's neighbours
        if(!seen[v[x][i]]){ // if neighbour wasen't visitetad
            dfs(v[x][i]); // call dfs of neighbour
        }
}

int main(){
    int components=0, x, y;
    fin >> nr_of_nodes >> nr_of_edges;
    for(int i=1; i<=nr_of_edges; i++){
        fin >> x >> y; // the coordonates of an edge
        v[x].push_back(y); // make y the neighbour of x
        v[y].push_back(x); // make x the neighbour of y
    }
    for(int i=1; i<=nr_of_nodes; i++)
        if(!seen[i])    dfs(i), components++;
    fout << components << " ";
    return 0;
}