Pagini recente » Cod sursa (job #80105) | Cod sursa (job #2818165) | Cod sursa (job #1735304) | Cod sursa (job #3031113) | Cod sursa (job #3249201)
// BFS orietated graph
// https://infoarena.ro/problema/bfs
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int NMAX = 1e5 + 5;
const int MMAX = 1e6 + 5;
int n, m, s;
int len[NMAX];
vector<vector<int>> gp(NMAX);
void BFS(int source)
{
queue<int> q;
q.push(source);
len[source] = 0;
while (!q.empty())
{
int node = q.front();
q.pop();
for (auto it : gp[node])
{
if (len[node] + 1 < len[it] || len[it] == 0)
{
len[it] = len[node] + 1;
q.push(it);
}
}
}
for (int i = 1; i <= n; i++)
if (len[i] == 0)
len[i] = -1;
}
int main()
{
fin >> n >> m >> s;
while (m--)
{
int x, y;
fin >> x >> y;
gp[x].push_back(y);
}
BFS(s);
for (int i = 1; i <= n; i++)
fout << len[i] << ' ';
fin.close();
fout.close();
return 0;
}