Pagini recente » Cod sursa (job #1654655) | Borderou de evaluare (job #2453670) | Cod sursa (job #184649) | Cod sursa (job #174188) | Cod sursa (job #2923572)
#include <iostream>
#include <fstream>
#include <deque>
using namespace std;
deque<int> neighbors[100001], nodes;
int n, m, s, x, y, neighbors_number[100001], cost[100001];
void BFS(int node) {
for (int i = 1; i <= n; ++i) {
cost[i] = -1;
}
cost[node] = 0;
nodes.push_back(node);
while (!nodes.empty()) {
/*
cout << "Nodes: ";
for (int i = 0; i < nodes.size(); ++i) {
cout << nodes[i] << ' ';
}
cout << "\n\nCost: ";
for (int i = 1; i <= n; ++i) {
cout << '[' << i << "] " << cost[i] << ' ';
}
cout << "\n\n";
*/
for (int i = 0; i < neighbors_number[nodes.front()]; ++i) {
if (cost[neighbors[nodes.front()][i]] == -1) {
nodes.push_back(neighbors[nodes.front()][i]);
cost[neighbors[nodes.front()][i]] = cost[nodes.front()] + 1;
}
}
nodes.pop_front();
}
}
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> n >> m >> s;
for (int i = 0; i < m; ++i) {
fin >> x >> y;
neighbors[x].push_back(y);
++neighbors_number[x];
}
BFS(s);
for (int i = 1; i <= n; ++i) {
fout << cost[i] << ' ';
}
return 0;
}