Pagini recente » Cod sursa (job #2406586) | Cod sursa (job #1772110)
#include "fstream"
#include "vector"
#include "queue"
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int INF = 1000000005;
const int NMAX = 100000;
int dist[NMAX];
int main() {
int N, M, S;
vector<int> graph[NMAX];
fin >> N >> M >> S;
for(int i = 1 ; i <= M ; i++) {
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
for(int i = 1 ; i <= N ; i++) {
if(i != S) {
dist[i] = INF;
}
}
queue<int> q;
q.push(S);
while(!q.empty()) {
int node = q.front();
q.pop();
for(int i = 0 ; i < graph[node].size() ; i++) {
if(dist[node] + 1 < dist[graph[node][i]]) {
dist[graph[node][i]] = dist[node] + 1;
q.push(graph[node][i]);
}
}
}
for(int i = 1 ; i <= N ; i++) {
if(dist[i] == INF) {
fout << "-1 ";
}
else {
fout << dist[i] << " ";
}
}
fout << "\n";
fin.close();
fout.close();
return 0;
}