Cod sursa(job #1694283)

Utilizator bogdandvDamaschin Bogdan-Valentin bogdandv Data 25 aprilie 2016 08:59:33
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

int m,n;
vector< vector <int> > graph;
vector<bool> visited;
void dfs(int vertex)
{	int i;
	//cout<<"!";
	if(vertex<0 || vertex>n-1)
		return;
	stack<int> myst;
	int element;
	bool found;
	myst.push(vertex);
	visited[vertex]=true;
	//cout<<"!";
	while(!myst.empty())
	{
		element=myst.top();
		//cout<<element<<" ";
		found=false;
		for(i=0;i<graph[element].size() && !found;i++)
			if(!visited[graph[element][i]])
			{
				found=true;
			}
		i--;
		if(found)
		{
			myst.push(graph[element][i]);
			visited[graph[element][i]]=true;
		}
		else myst.pop();
	}
	//cout<<"\n";
}

int main()
{
	ifstream f("dfs.in");
	ofstream g("dfs.out");
	f>>n>>m;
	graph.resize(n);
	visited.resize(n,false);
	int x,y;
	for(int i=0;i<m;i++)
	{
		f>>x>>y;
		x--;
		y--;
		graph[x].push_back(y);
		graph[y].push_back(x);
	}
	int nr=0;
	for(int i=0;i<n;i++)
		if(!visited[i])
		{nr++;
		dfs(i);
		//cout<<i;
		}
	g<<nr;
    return 0;
}