Pagini recente » Cod sursa (job #1312888) | Cod sursa (job #2984624) | Cod sursa (job #2834554) | Cod sursa (job #2443373) | Cod sursa (job #1370278)
#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;
}