Cod sursa(job #1711000)

Utilizator srefan1Oncioiu Stefan srefan1 Data 30 mai 2016 09:56:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
int n, m, source;

vector < vector <int> >graph;
vector<int>visited;

void BFS(int vertex)
{
	if ((vertex<0) || (vertex>n - 1))
	{
		return;
	}
	queue <int> q;
	int element;
	q.push(vertex);
	visited[vertex] = 0;

	while (!q.empty())
	{
		element = q.front();
		for (int 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();
	}

}


int main()
{
	int x, y;
	ifstream f("bfs.in");
	ofstream g("bfs.out");
	f >> n >> m >> source;
	source--;
	graph.resize(n);
	visited.resize(n, -1);

	for (int i = 0; i<m; i++)

	{
		f >> x >> y;
		x--;
		y--;
		graph[x].push_back(y);
	}


	BFS(source);
	for (int j = 0; j<n; j++)
	{
		g << visited[j] << " ";
	}
	return 0;
}