Pagini recente » Statistici Jega Alexandru (Allex_Sirius97) | Cod sursa (job #3333834) | Cod sursa (job #749696) | Cod sursa (job #987045) | Cod sursa (job #3318488)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ifstream fin("bfs.in");
ofstream fout("bfs.out");
if (!fin) return 0;
int N, M, S;
fin >> N >> M >> S;
vector<vector<int>> g(N + 1);
for (int i = 0; i < M; ++i) {
int x, y;
fin >> x >> y;
if (x >= 1 && x <= N && y >= 1 && y <= N)
g[x].push_back(y); // orientat: doar din x spre y
}
vector<int> dist(N + 1, -1);
queue<int> q;
dist[S] = 0;
q.push(S);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : g[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
for (int i = 1; i <= N; ++i)
fout << dist[i] << " ";
fout << "\n";
return 0;
}