Pagini recente » Cod sursa (job #101659) | Cod sursa (job #2428632) | Cod sursa (job #1106284) | Cod sursa (job #670366) | Cod sursa (job #2796654)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector<int> graph[100005];
queue<int> q;
int vis[100005], nod, d[100005];
void bfs(int node)
{
q.push(node);
vis[node] = true;
while(!q.empty())
{
node = q.front();
q.pop();
for (int i = 0; i < graph[node].size(); i++)
{
int next = graph[node][i];
if (!vis[next] and d[next] != 0)
{
d[next] = d[node] + 1;
q.push(next);
vis[next] = true;
}
}
}
}
int main()
{
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s, x, y;
fin >> n >> m >> s;
for (int i = 1; i <= m; i++)
{
fin >> x >> y;
graph[x].push_back(y);
}
d[s] = 0;
bfs(s);
for (int i = 1; i <= n; i++)
if (!vis[i])
d[i] = -1;
for (int i = 1; i <= n; i++)
fout << d[i] << " ";
return 0;
}