Cod sursa(job #2596187)

Utilizator CharacterMeCharacter Me CharacterMe Data 9 aprilie 2020 13:23:47
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>

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

int n, m, start;
int sol[100005];
vector<int> graph[100005];
queue<int> q;

void bfs();

int main()
{

    fin >> n >> m >> start;

    for(int i = 1; i <= n; ++i) sol[i] = -1;
    sol[start] = 0;

    while(m--){
        int x, y;
        fin >> x >> y;

        graph[x].push_back(y);
    }

    bfs();

    for(int i = 1; i <= n; ++i) fout << sol[i] << " ";

    return 0;
}

void bfs(){
    q.push(start);

    while(!q.empty()){
        int now = q.front(); q.pop();

        for(auto next:graph[now]){
            if(sol[next] != -1) continue;

            sol[next] = sol[now] + 1;
            q.push(next);
        }
    }
}