Pagini recente » Cod sursa (job #1214249) | Cod sursa (job #1214845) | Cod sursa (job #785094) | Cod sursa (job #742775) | Cod sursa (job #3156005)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int main() {
const int NMAX = 100000;
int N, M, S;
f >> N >> M >> S;
vector <int> G[N + 1];
int vis[NMAX + 1] = {0};
int d[NMAX + 1] = {-1};
for(int i = 1; i <= M; i++) {
int x, y;
f >> x >> y;
G[x].push_back(y);
}
queue<int> q;
q.push(S);
d[S] = 0;
vis[S] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto next : G[x]) {
if (vis[next] == 0) {
q.push(next);
vis[next] = 1;
d[next] = d[x] + 1;
}
}
}
for(int i = 1; i <= N; i++) {
if(d[i] == 0 && i != S) d[i] = -1;
cout << d[i] << " ";
}
}