Pagini recente » Cod sursa (job #2346240) | Cod sursa (job #1177242) | Cod sursa (job #2155901) | Cod sursa (job #2587238) | Cod sursa (job #2960587)
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
const int MAX_SIZE = 100001;
int n, m, s;
deque<int> nodes, neighbors[MAX_SIZE];
vector<int> cost;
void graph_traversal(int node) {
for (int i = 0; i <= n; ++i) {
cost.push_back(-1);
}
cost[node] = 0;
nodes.push_back(node);
while (!nodes.empty()) {
int curr_node = nodes.front();
nodes.pop_front();
for (auto i = neighbors[curr_node].begin(); i != neighbors[curr_node].end(); ++i) {
if (cost[*i] == -1) {
cout << *i << endl;
nodes.push_back(*i);
cost[*i] = cost[curr_node] + 1;
}
}
}
}
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> n >> m >> s;
for (int i = 0; i < m; ++i) {
int x, y;
fin >> x >> y;
neighbors[x].push_back(y);
}
graph_traversal(s);
for (int i = 1; i <= n; ++i) {
fout << cost[i] << ' ';
}
return 0;
}