Pagini recente » Cod sursa (job #86772) | Cod sursa (job #1545938) | Cod sursa (job #1022749) | Cod sursa (job #1949876) | Cod sursa (job #2952640)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
bool viz[100001];
int dist[100001];
int n, m, s, x, y;
vector<int> a[100001];
void bfs(int start) {
queue<int> q;
q.push(start);
viz[start] = 1;
int d = 0;
while (!q.empty()) {
int t = q.front();
q.pop();
for (int x : a[t]) {
if (!viz[x]) {
q.push(x);
dist[x] = dist[t] + 1;
viz[x] = 1;
}
}
}
}
void dfs(int start) {
for (int x : a[start]) {
if (!viz[x]) {
viz[x] = 1;
dfs(x);
}
}
}
int main() {
fin >> n >> m >> s;
for (int i = 0; i < m; i++) {
fin >> x >> y;
a[x].push_back(y);
}
bfs(s);
for (int i = 1; i <= n; i++) {
if (viz[i]) {
fout << dist[i] << " ";
} else {
fout << "-1 ";
}
}
}