Pagini recente » Cod sursa (job #266211) | Cod sursa (job #2248432) | Cod sursa (job #139970) | Cod sursa (job #1196517) | Cod sursa (job #1508226)
//
// main.cpp
// BFS
//
// Created by Mihai Visuian on 22/10/2015.
// Copyright © 2015 Mihai Visuian. All rights reserved.
//
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<vector<int> > g;
vector<int> cost;
queue<int>q;
void BFS (int x) {
cost[x]=0;
int in = x;
q.push(x);
for(;!q.empty();q.pop()) {
x = q.front();
for (vector<int>::iterator it = g[x].begin(); it != g[x].end(); it++) {
if (!cost[*it] && *it != in) {
q.push(*it);
cost[*it] = cost[x]+1;
}
}
}
}
int main(int argc, const char * argv[]) {
int n, m, s, x, y;
fin >> n >> m >> s;
g.resize(n+1);
cost.assign(n+1,0);
for (int i = 0; i < m; i++) {
fin >> x >> y;
g[x].push_back(y);
}
BFS(s);
for (int i = 1; i<= n; i++ ) {
if (!cost[i] && i != s) {
cost[i] = -1;
}
fout << cost[i] << ' ';
}
fin.close();
fout.close();
return 0;
}