Pagini recente » Cod sursa (job #864937) | Cod sursa (job #2538475) | Cod sursa (job #1792580) | Cod sursa (job #1525952) | Cod sursa (job #2446037)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
const int dim = 100005;
int n,m,s;
int dist[dim];
vector <int> v[dim];
queue <int> pq;
void BFS(int s)
{
int nod;
pq.push(s);
dist[s] = 1;
while (!pq.empty())
{
nod = pq.front();
pq.pop();
for (int i=0; i<v[nod].size(); i++)
{
if (dist[v[nod][i]] >= dist[nod] + 1)
{
dist[v[nod][i]] = dist[nod] + 1;
pq.push(v[nod][i]);
}
}
}
}
int main()
{
int x,y;
in >> n >> m >> s;
for (int i=1; i<=m; i++)
{
in >> x >> y;
v[x].push_back(y);
}
for (int i=1; i<=n; i++)
{
dist[i] = dim;
}
BFS(s);
for (int i=1; i<=n; i++)
{
if (dist[i] == dim)
{
out << "-1 ";
}
else out << dist[i] - 1 << " ";
}
return 0;
}