Cod sursa(job #2952640)

Utilizator Chiri_Robert Chiributa Chiri_ Data 9 decembrie 2022 17:34:53
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

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

bool viz[100001];
int dist[100001];
int n, m, s, x, y;
vector<int> a[100001];

void bfs(int start) {
    queue<int> q;
    q.push(start);
    viz[start] = 1;
    int d = 0;

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

        for (int x : a[t]) {
            if (!viz[x]) {
                q.push(x);
                dist[x] = dist[t] + 1;
                viz[x] = 1;
            }
        }
    }
}

void dfs(int start) {
    for (int x : a[start]) {
        if (!viz[x]) {
            viz[x] = 1;
            dfs(x);
        }
    }
}

int main() {
    fin >> n >> m >> s;
    for (int i = 0; i < m; i++) {
        fin >> x >> y;
        a[x].push_back(y);
    }
    bfs(s);

    for (int i = 1; i <= n; i++) {
        if (viz[i]) {
            fout << dist[i] << " ";
        } else {
            fout << "-1 ";
        }
    }
}