Pagini recente » Cod sursa (job #705102) | Cod sursa (job #1255741) | Cod sursa (job #2906299) | Cod sursa (job #2340735) | Cod sursa (job #2639294)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
int n, m, s, dist[100001], x, y;
vector < int > ma[100001];
queue < int > q;
void bfs (int p) {
for (int i = 1; i <= n; i++)
dist[i] = -1;
dist[p] = 0;
q.push (p);
while (not q.empty ()) {
int nc = q.front ();
q.pop ();
for (int i = 0; i < ma[nc].size (); i++) {
if (dist[ma[nc][i]] == -1) {
dist[ma[nc][i]] = dist[nc] + 1;
q.push (ma[nc][i]);
}
}
}
}
int main()
{
fin >> n >> m >> s;
for (int i = 1; i <= m; i++) {
fin >> x >> y;
ma[x].push_back (y);
}
bfs (s);
for (int i = 1; i <= n; i++)
fout << dist[i] << ' ';
return 0;
}