Cod sursa(job #2981448)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 17 februarie 2023 22:49:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <vector>
#include <queue>
#define DIM 100005

using namespace std;

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

int n, m, source, dist[DIM];
vector<int> edges[DIM];
queue<int> q;

void bfs(int node) {
    dist[node] = 1;
    q.push(node);
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (auto x: edges[node]) {
            if (dist[x] == 0) {
                dist[x] = dist[node] + 1;
                q.push(x);
            }
        }
    }
}

int main() {
    f >> n >> m >> source;

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

    bfs(source);

    for (int i = 1; i <= n; i++) {
        g << dist[i] - 1 << " ";
    }

    return 0;
}