Cod sursa(job #1618525)

Utilizator bragaRObragaRO bragaRO Data 27 februarie 2016 21:04:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <cstdlib>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;



int m, n;
vector <vector <int> > graph;
vector <int> visited;
ifstream f("bfs.in");
ofstream h("bfs.out");


void bfs(int vertex,int n)
{
	if (vertex<0 || vertex>n - 1) return;

	queue <int> q;
	int element, i;
	bool found;

	q.push(vertex);

	for(i=0;i<n;i++) visited[i]=-1;
	visited[vertex] = 0;

	while (!q.empty())
	{
		element = q.front();
		for (i = 0; i < graph[element].size(); i++)
			if (visited[graph[element][i]]==-1)
			{
				q.push(graph[element][i]);
				visited[graph[element][i]] = visited[element]+1;
			}
		q.pop();
	}

	for (i = 0; i < visited.size(); i++) h << visited[i] << " ";
	h << "\n";
}


int main()
{
	int x, y, i,a,nod;
	f >> n >> m >> nod;
    nod--;
	graph.resize(n);
	visited.resize(n, false);

	for (i = 0; i<m; i++)
	{
		f >> x >> y;
		x--; y--;
		graph[x].push_back(y);
	}

	bfs(nod,n);

	f.close();
	h.close();
	return 0;
}