Cod sursa(job #2597061)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 11 aprilie 2020 09:22:44
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, s, ans[100005], x,  y;
vector <int> graph[100005];

void bfs() {
    queue <int> breadthSearch;
    breadthSearch.push(s);

    memset(ans, -1, sizeof(ans));
    ans[s] = 0;

    while(breadthSearch.size()) {
        int adj = breadthSearch.front();
        breadthSearch.pop();
        for(int a: graph[adj]) {
            if(ans[a] == -1) {
                ans[a] = ans[adj] + 1;
                breadthSearch.push(a);
            }
        }
    }
}

int main()
{
    in >> n >> m >> s;
    for(int i = 1; i <= m; i++) {
        in >> x >> y;
        graph[x].push_back(y);
    }
    bfs();
    for(int i = 1; i <= n; i++) {
        out << ans[i] << ' ';
    }
    return 0;
}