Pagini recente » Cod sursa (job #403449) | Cod sursa (job #1356094) | Cod sursa (job #2674073) | Cod sursa (job #2778561) | Cod sursa (job #2802240)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int N_MAX = 1e5;
bool v[N_MAX + 1][N_MAX + 1];
void BFS(int start, int n) {
int dist[N_MAX + 1] = {0};
dist[start] = 1;
queue<int> q;
q.push(start);
while (!q.empty()) {
for (int i = 1; i <= n; ++i) {
if (v[q.front()][i] && !dist[i]) {
dist[i] = dist[q.front()] + 1;
q.push(i);
}
}
q.pop();
}
for (int i = 1; i <= n; ++i) {
if (dist[i]) {
cout << dist[i] - 1;
} else {
fout << -1;
}
fout << ' ';
}
}
int main() {
fin.tie(0);
std::ios_base::sync_with_stdio(0);
int n, m, s;
fin >> n >> m >> s;
while (m--) {
int x, y;
fin >> x >> y;
v[x][y] = 1;
}
BFS(s, n, v);
}