Pagini recente » Cod sursa (job #1648494) | Cod sursa (job #1823238) | Cod sursa (job #242505) | Cod sursa (job #2981772) | Cod sursa (job #2960446)
#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())
{
/*
cout << "Nodes: ";
for (auto i = nodes.begin(); i != nodes.end(); ++i) {
cout << *i << ' ';
}
cout << "\n\nCost: ";
for (int i = 1; i <= n; ++i) {
cout << '[' << i << "] " << cost[i] << ' ';
}
cout << "\n\n";
*/
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;
}