Pagini recente » Cod sursa (job #1360580) | Cod sursa (job #2379528)
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <vector>
#include <queue>
#define MAX 100005
using namespace std;
int n, m, s;
int distanta[MAX];
vector<int> graf[MAX];
queue<int> q;
ifstream f("bfs.in");
ofstream o("bfs.out");
void print()
{
for (int i = 1; i <= n; i++)
o << distanta[i] << " ";
}
void bfs()
{
int current, next;
while (!q.empty())
{
current = q.front();
q.pop();
for (int i = 0; i < graf[current].size(); i++)
{
next = graf[current][i];
if (distanta[next] == -1)
{
q.push(next);
distanta[next] = distanta[current] + 1;
}
}
}
}
int main()
{
f >> n >> m >> s;
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
graf[x].push_back(y);
}
for (int i = 1; i <= n; i++)
distanta[i] = -1;
distanta[s] = 0;
q.push(s);
bfs();
print();
return 0;
}