Pagini recente » Cod sursa (job #2088625) | Cod sursa (job #1451885) | Cod sursa (job #2185482) | Cod sursa (job #2591277) | Cod sursa (job #1053982)
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <vector>
using namespace std;
#define maxn 1001
#define INF 20000000
vector<int> gr[maxn];
queue<int> q;
int dist[maxn], color[maxn];
int n, m, s;
void bfs( int start ){
int u,v;
//initialize the cost
for( int i = 1; i <=n; ++i ){
dist[i] = -1;
color[i] = 1;
}
q.push(start);
dist[s] = 0;
color[s] = 0;
while(!q.empty()){
u = q.front();
q.pop();
//for all the childs
for( int i = 0; i < gr[u].size(); ++i ){
v = gr[u][i];
if( color[v] == 1 ){
dist[v] = dist[u] + 1;
color[v] = 0;
q.push(v);
}
}
}
}
int main(){
freopen("bfs.in", "r", stdin);
freopen("bfs.out", "w", stdout);
int i,x,y;
//read the first line
scanf("%d %d %d ", &n, &m, &s);
//read the list of edges and construct the graph
for (i = 1; i <=m; ++i) {
scanf("%d %d ", &x, &y);
gr[x].push_back(y);
}
bfs(s);
for (i = 1; i <= n; i++)
printf("%d ", dist[i]);
printf("\n");
return 0;
}