Cod sursa(job #2219151)

Utilizator mirunazMiruna Zavelca mirunaz Data 7 iulie 2018 14:57:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

#define N 100001

vector <int> v[N];
queue <int> q;
int viz[N], lvl[N];

void bfs (int node)
{
    viz[node] = 1;
    q.push (node);
    lvl[node] = 1;

    while (!q.empty ()){
        node = q.front ();
        q.pop ();
        int n = v[node].size ();

        for (int i=0; i<n; i++){
            int now = v[node][i];
            if (viz[now] == 0){
                viz[now] = 1;
                lvl[now] = lvl[node] + 1;
                q.push (now);
            }
        }
    }
}

int main ()
{
    ifstream in ("bfs.in");
    ofstream out ("bfs.out");
    int n, m, s;
    in >> n >> m >> s;

    for (int i=1; i<=m; i++){
        int x, y;
        in >> x >> y;
        v[x].push_back (y);
    }

    bfs (s);

    for (int i=1; i<=n; i++){
        out << lvl[i] - 1 << " ";
    }

    return 0;
}