Cod sursa(job #2138207)

Utilizator sulzandreiandrei sulzandrei Data 21 februarie 2018 14:16:04
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
int d[100003];
vector<int> v[100003];
bool visited[100003]{false};
queue<int> que;
void bfs(int start,int n)
{
    for(int i =1 ; i<= n ; i++)
        d[i] = 1<<31;
    d[start]=0;
    que.push(start);
    int nod;
    while(!que.empty())
    {
        nod = que.front(); que.pop();
        visited[nod] = true;
        for(int neighbour : v[nod])
        {
            if (!visited[neighbour] )
            {
                d[neighbour] = d[nod]+1;
                que.push(neighbour);
            }
        }
    }

}
int main()
{
    int n,m,s;
    in >> n >> m >> s;
    int x,y;
    for(int i  =0 ; i < m ; i++)
    {
        in >> x >> y;
        v[x].push_back(y);
    }
    bfs(s,n);
    for(int i = 1 ; i <= n ; i++)
       if(d[i] == (1<<31))
        out<<"-1 ";
       else
        out<<d[i]<<" ";
    return 0;
}