Pagini recente » Cod sursa (job #1567747) | Cod sursa (job #1564520) | Cod sursa (job #987249) | Cod sursa (job #2714878) | Cod sursa (job #1711000)
#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;
}