Pagini recente » Cod sursa (job #423830) | Cod sursa (job #2741683) | Istoria paginii runda/22_februarie_simulare_oji_2024_clasa_9 | Istoria paginii utilizator/laviniadragne | Cod sursa (job #2330946)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream gout("bfs.out");
queue <int> q;
vector <int> graph[100001];
int viz[100001], dist[100001];
void bfs(int start)
{
q.push(start);
viz[start] = 1;
dist[start] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
for (int j = 0; j < graph[nod].size(); j++)
{
if (viz[graph[nod][j]] == 0)
{
q.push(graph[nod][j]);
viz[graph[nod][j]] = 1;
dist[graph[nod][j]] = dist [nod] + 1;
}
}
}
}
int main()
{
int i, n, m, x, y, s;
fin >> n >> m >> s;
for (i = 1; i <= m; i++)
{
fin >> x >> y;
graph[x].push_back(y);
}
bfs(s);
for(i = 1; i <= n; i++)
{ if (dist[i] != 0 or i==s) gout << dist[i] - 1 << " ";
else gout << -1 << " ";
}
return 0;
}