Cod sursa(job #3196597)

Utilizator jasminePopa Jasmine jasmine Data 24 ianuarie 2024 12:35:45
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>

using namespace std;

const int nmax = 100000;
vector<int> G[nmax + 1];
int vis[nmax + 1], d[nmax + 1];

void BFS(int s) {
    queue<int> q;
    q.push(s);
    d[s] = 0;
    vis[s] = 1;

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

        for (auto next : G[x]) {
            if (!vis[next]) {
                q.push(next);
                d[next] = d[x] + 1;
                vis[next] = 1;
            }
        }
    }
}

int main() {
    int n, m, s;

    cin >> n >> m >> s;

    memset(d, -1, sizeof(d)); // Inițializăm toate distanțele cu -1

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

    BFS(s);

    for (int i = 1; i <= n; i++) {
        cout << d[i] << " ";
    }


    return 0;
}