Pagini recente » Cod sursa (job #2290493) | Cod sursa (job #528167) | Cod sursa (job #1816496) | Cod sursa (job #504330) | Cod sursa (job #3272530)
#include <bits/stdc++.h>
using namespace std;
vector <int> graph[200005]; // graph[x] - retine vecinii nodului x
int distances[200005];
const int INF = 1e9;
void bfs(int n, int source) {
for (int i = 1; i <= n; i++) {
distances[i] = INF;
}
distances[source] = 0;
queue<int> q;
q.push(source);
while (!q.empty()) {
auto node = q.front();
q.pop();
for (auto neighbor : graph[node]) {
if (distances[neighbor] > distances[node] + 1) {
distances[neighbor] = distances[node] + 1;
q.push(neighbor);
}
}
}
for (int i = 1; i <= n; i++) {
if (distances[i] == INF) distances[i] = -1;
cout << distances[i] << " ";
}
}
int main() {
freopen("bfs.in", "r", stdin);
freopen("bfs.out", "w", stdout);
int n, m, source;
cin >> n >> m >> source;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
}
bfs(n, source);
}