Pagini recente » Cod sursa (job #1120102) | Cod sursa (job #2377713) | Cod sursa (job #2903998) | Cod sursa (job #2627183) | Cod sursa (job #2383951)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define MAXN 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, nod;
vector <int> G[MAXN];
void citire () {
fin >> n >> m >> nod;
for (int i = 0; i < m; ++i) {
int x, y;
fin >> x >> y;
G[x].push_back(y);
}
}
void bfs (int nod) {
queue <int> Q;
int V[MAXN] = {0}, Dist[MAXN] = {0};
Dist[nod] = 0;
V[nod]++;
Q.push(nod);
while (!Q.empty()) {
int x = Q.front();
Q.pop();
int size = G[x].size();
for (int i = 0; i < size; ++i) {
int y = G[x][i];
if (!V[y]) {
Q.push(y);
V[y]++;
Dist[y] = Dist[x] + 1;
}
}
}
for (int i = 1; i <= n; ++i) {
if (V[i]) {
fout << Dist[i] << " ";
}
else {
fout << -1 << " ";
}
}
}
int main () {
citire();
bfs(nod);
}