Pagini recente » Cod sursa (job #1830692) | Cod sursa (job #1704146) | Cod sursa (job #1587552) | Cod sursa (job #3122820) | Cod sursa (job #3155997)
// BFS
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int nmax = 1e5;
int d[nmax + 1];
bool viz[nmax + 1];
int n, m, s;
queue <int> q;
vector <int> g[nmax + 1];
void Citire() {
fin >> n >> m >> s;
for (int i = 1; i <= m; i++) {
int x, y;
fin >> x >> y;
g[x].push_back(y);
}
}
void BFS(int x) {
q.push(x);
viz[x] = 1;
d[x] = 0;
while (!q.empty()) {
int nod = q.front();
q.pop();
for (auto vecin : g[nod]) {
if (!viz[vecin]) {
viz[vecin] = 1;
d[vecin] = d[nod] + 1;
q.push(vecin);
}
}
}
}
void Afisare() {
for (int i = 1; i <= n; i++) {
if (d[i] == 0 && i != s)
fout << -1 << " ";
else
fout << d[i] << " ";
}
}
int main()
{
Citire();
BFS(s);
Afisare();
return 0;
}