Pagini recente » Cod sursa (job #614728) | Cod sursa (job #1028281) | Cod sursa (job #1887460) | Cod sursa (job #222190) | Cod sursa (job #2870770)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("BFS.in");
ofstream fout("BFS.out");
const int NMAX = 100005;
int n, m, s;
vector < int > L[NMAX];
queue < int > Q;
int dist[NMAX];
void citire()
{
int x, y;
fin >> n >> m >> s;
for(int i = 1; i <= m; i++)
{
fin >> x >> y;
L[x].push_back(y);
}
}
void BFS()
{
int nod;
for(int i = 1; i <= n; i++)
{
dist[i] = 1e9;
}
Q.push(s);
dist[s] = 0;
while(!Q.empty())
{
nod = Q.front();
Q.pop();
for(auto it : L[nod])
{
if(dist[it] == 1e9)
{
dist[it] = 1 + dist[nod];
Q.push(it);
}
}
}
}
void afisare()
{
for(int i = 1; i <= n; i++)
{
if(dist[i] == 1e9)
{
fout << -1 << " ";
}
else
{
fout << dist[i] << " ";
}
}
}
int main()
{
citire();
BFS();
afisare();
return 0;
}