Pagini recente » Cod sursa (job #874619) | Cod sursa (job #146583) | Cod sursa (job #1775856) | Cod sursa (job #2812067) | Cod sursa (job #2435963)
#include <bits/stdc++.h>
#define Nmax 100005
#define oo (1 << 30)
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, startNode;
int Distances[Nmax];
vector < int > Graph[Nmax];
queue < int > Q;
void BFS(int startNode)
{
Q.push(startNode);
while(Q.empty() == 0)
{
int node = Q.front();
Q.pop();
for(int i = 0; i < Graph[node].size(); ++i)
if(Distances[Graph[node][i]] == oo)
{
Q.push(Graph[node][i]);
Distances[Graph[node][i]] = 1 + Distances[node];
}
}
}
int main()
{
fin >> N >> M >> startNode;
for(int i = 1; i <= M; ++i)
{
int home, destination;
fin >> home >> destination;
Graph[home].push_back(destination);
}
for(int i = 1; i <= N; ++i)
Distances[i] = oo;
Distances[startNode] = 0;
BFS(startNode);
for(int i = 1; i <= N; ++i)
if(Distances[i] == oo)
fout << -1 << " ";
else
fout << Distances[i] << " ";
return 0;
}