Pagini recente » Cod sursa (job #1785579) | Cod sursa (job #1766519) | Cod sursa (job #372241) | Cod sursa (job #3124350) | Cod sursa (job #2923670)
#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;
}