Cod sursa(job #3235500)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 18 iunie 2024 10:12:31
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>
using namespace std;

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

signed main() {
    int n, m, s;
    fin >> n >> m >> s;
    vector<vector<int>> graph(n + 1);
    vector<int> d(n + 1, -1);
    vector<bool> visited(n, false);
    queue<int> nodes;
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }
    nodes.push(s);
    visited[s] = true;
    d[s] = 0;
    while (!nodes.empty()) {
        int current = nodes.front();
        nodes.pop();
        for (int node : graph[current]) {
            if (!visited[node]) {
                nodes.push(node);
                visited[node] = true;
                d[node] = d[current] + 1;
            }
        }
    }
    for (int distance : d) {
        fout << distance << " ";
    }
    return 0;
}