Pagini recente » Cod sursa (job #1339037) | Cod sursa (job #2125277) | Cod sursa (job #2283860) | Cod sursa (job #2440333) | Cod sursa (job #2088670)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
int main()
{
const int Inf = 100001;
ifstream f_in("bfs.in");
int N_nodes = 0;
f_in >> N_nodes;
int N_arches = 0;
f_in >> N_arches;
int start = 0;
f_in >> start;
int *p = &N_nodes;
int a[*p][*p];
for (int i = 0; i < N_nodes; i++){
for (int j = 0; j < N_nodes; j++)
a[i][j] = 0;
}
for (int i = 0; i < N_arches; i++){
int tmp_i, tmp_j;
f_in >> tmp_i; f_in>>tmp_j;
a[tmp_i-1][tmp_j-1] = 1;
}
f_in.close();
queue<int> coada;
int nodes[*p][2];
for (int i = 0; i < N_nodes; i++){
nodes[i][0] = 0;
nodes[i][1] = Inf;
}
coada.push(start-1);
nodes[start-1][1] = 0;
while (!coada.empty()){
int node = coada.front();
coada.pop();
nodes[node][0] = 2;
for (int j = 0; j < N_nodes; j++){
if (a[node][j] == 1 && nodes[j][0] == 0){
coada.push(j);
nodes[j][0] = 1;
nodes[j][1] = nodes[node][1]+1;
}
}
}
ofstream f_out("bfs.out");
for (int i = 0; i < N_nodes; i++){
if (nodes[i][1] != Inf) f_out<<nodes[i][1]<<" "; else f_out<<-1<<" ";
}
f_out.close();
return 0;
}