Cod sursa(job #1053980)

Utilizator quarianPetreanu Alexandru quarian Data 13 decembrie 2013 07:52:37
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#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 1;
}