Cod sursa(job #2571225)

Utilizator vmnechitaNechita Vlad-Mihai vmnechita Data 4 martie 2020 21:47:38
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <bits/stdc++.h>
#define NMAX 100005

using namespace std;

ifstream fin ("bfs.in");
ofstream fout ("bfs.out");

queue < int > q;
vector < int > v[NMAX];
int viz[NMAX];

void bfs ( int nod );

int main()
{
    int n, m, k, x, y, i;

    fin >> n >> m >> k;
    while ( m-- )
    {
        fin >> x >> y;
        v[x].push_back ( y );
    }

    bfs ( k );

    for ( i = 1 ; i <= n ; i++ ) fout << viz[i] - 1 << ' ';

    return 0;
}

void bfs ( int nod )
{
    int x, i;

    q.push ( nod );
    viz[nod] = 1;
    while ( q.empty() == 0 )
    {
        x = q.front();
        q.pop();

        for ( i = 0 ; i < v[x].size() ; i++ ) if ( viz[v[x][i]] == 0 ) q.push ( v[x][i] ), viz[v[x][i]] = viz[x] + 1;
    }
}