Cod sursa(job #2817251)

Utilizator TudoseSanzianaTudose Sanziana TudoseSanziana Data 13 decembrie 2021 12:28:07
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <bits/stdc++.h>
using namespace std;

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

const int N_MAX = 1e5;

int n, m, s;
vector<int> gr[N_MAX + 5];
int ans[N_MAX + 5];

int main() {
    in >> n >> m >> s;

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

    queue<int> q;

    q.push(s);
    ans[s] = 1;
    while (!q.empty()) {
        int front = q.front();
        for (int i = 0; i < gr[front].size(); i++)
            if (!ans[gr[front][i]]) {
                ans[gr[front][i]] = ans[front] + 1;
                q.push(gr[front][i]);
            }

        q.pop();
    }

    for (int i = 1; i <= n; i++) out << ans[i] - 1 << " ";
    out << '\n';

    return 0;
}