Pagini recente » Cod sursa (job #752799) | Cod sursa (job #1180963)
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;
int main() {
ifstream in;
in.open("bfs.txt");
ofstream out;
out.open("bfs.out");
int N, M, S, i, n1, n2, x;
in >> N >> M >> S;
vector<int> nodes[2*N];
vector<int>::iterator it;
int dist[100100] = {0}, vizitat[100100] = {0};
queue<int> q;
for (i = 0; i < M; i++) {
in >> n1 >> n2;
if (n1 != n2)
nodes[n1].push_back(n2);
}
q.push(S);
while (!q.empty()) {
x = q.front();
for (it = nodes[x].begin(); it != nodes[x].end(); it++) {
if (vizitat[*it] == 0) {
vizitat[*it] = 1;
dist[*it] = dist[x] + 1;
//cout << *it << " ";
q.push(*it);
}
}
vizitat[x] = -1;
q.pop();
}
//cout << endl;
for (i = 1; i <= N; i++) {
if (i == S)
out << "0" << " ";
else if (dist[i] != 0)
out << dist[i] << " ";
else
out << "-1" << " ";
}
in.close();
out.close();
return 0;
}