Pagini recente » Cod sursa (job #2683612) | Cod sursa (job #2226570) | Cod sursa (job #2172955) | Cod sursa (job #1733447) | Cod sursa (job #3196599)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
const int nmax = 100000;
vector<int> G[nmax + 1];
int vis[nmax + 1], d[nmax + 1];
void BFS(int s) {
queue<int> q;
q.push(s);
d[s] = 0;
vis[s] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto next : G[x]) {
if (!vis[next]) {
q.push(next);
d[next] = d[x] + 1;
vis[next] = 1;
}
}
}
}
int main() {
int n, m, s;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> n >> m >> s;
memset(d, -1, sizeof(d)); // Inițializăm toate distanțele cu -1
for (int i = 1; i <= m; i++) {
int x, y;
fin >> x >> y;
G[x].push_back(y);
}
BFS(s);
for (int i = 1; i <= n; i++) {
fout << d[i] << " ";
}
fin.close();
fout.close();
return 0;
}