Cod sursa(job #3154121)

Utilizator maraa13Spataru Mara-Andreea maraa13 Data 3 octombrie 2023 12:51:45
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;
const int nmax = 10000;
vector<int> a[nmax + 1]; 
int n, m, s, x, y;       
const int INF = INT_MAX; // valoare folosita pt nodurile inaccesibile
int d[nmax + 1];         // distanta de la nodul sursa la nodul i
queue<int> q; 

int main() {
    ifstream f("bfs.in");
    f >> n >> m >> s;
    while (m--) {
        f >> x >> y;
        a[x].push_back(y);
    }
    f.close();

    //initializez distanta cu infinit pt a marca nodurile inaccesibile
    for (int i = 1; i <= n; i++) {
        d[i] = INF;
    }

    // Parcurgere BFS
    q.push(s);
    d[s] = 0;

    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (int i = 0; i < a[x].size(); i++) {
            int y = a[x][i];
            if (d[y] == INF) { //verificam daca nodul y a fost vizitat
                d[y] = d[x] + 1;
                q.push(y);
            }
        }
    }

    // Afisare distante
    for (int i = 1; i <= n; i++) {
        if (d[i] == INF) {
            cout << -1 << " "; // la nod nu se poate ajungeS
        } else {
            cout << d[i] << " ";
        }
    }
    cout << endl;
}