Pagini recente » Borderou de evaluare (job #3032037) | Cod sursa (job #1698944)
// BFS v1.0.cpp : Defines the entry point for the console application.
//
#include "iostream"
#include "fstream"
#include "vector"
#include "stack"
using namespace std;
int m, n, s;
vector<vector<int>> graph;
vector<char> nod_color;
vector<int> nod_distance;
ifstream bfs_in("bfs.in");
ofstream bfs_out("bfs.out");
void bfs(int nod)
{
int i;
stack<int> s;
nod_color[nod] = 'B';
if (nod_distance[nod] == -1)
nod_distance[nod] = 0;
for (i = 0; i < graph[nod].size(); i++)
if (nod_color[graph[nod][i]] == 'W')
{
nod_color[graph[nod][i]] = 'G';
nod_distance[graph[nod][i]] = nod_distance[nod] + 1;
s.push(graph[nod][i]);
}
while (!s.empty())
{
bfs(s.top());
s.pop();
}
}
int main()
{
int x, y;
bfs_in >> n >> m >> s;
s--;
graph.resize(n);
nod_color.resize(n, 'W');
nod_distance.resize(n, -1);
for (int i = 0; i < m; i++)
{
bfs_in >> x >> y;
x--;
y--;
graph[x].push_back(y);
}
bfs(s);
for (int i = 0; i < nod_distance.size(); i++)
bfs_out << nod_distance[i] << ' ';
return 0;
}