Cod sursa(job #3316914)

Utilizator gpl12Giulia gpl12 Data 21 octombrie 2025 13:41:32
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

int n, m, s;
const int MAXN = 10000 + 5;
vector<int> l[MAXN];
int d[MAXN];
int viz[MAXN];

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

    while (!q.empty()) {
        int x = q.front(); q.pop();
        for (int y : l[x]) {
            if (!viz[y]) {
                q.push(y);
                viz[y] = 1;
                d[y] = d[x] + 1;
            }
        }
    }
}

int main() {
    ifstream fin("bfs.in");
    fin >> n >> m >> s;

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

    for (int i = 1; i <= n; i++) {
        d[i] = -1;
        viz[i] = 0;
    }

    BFS(s);

    ofstream fout("bfs.out");
    for (int i = 1; i <= n; i++) {
        fout << d[i] << " ";
    }
    fout.close();

    return 0;
}
// TIP See CLion help at <a
// href="https://www.jetbrains.com/help/clion/">jetbrains.com/help/clion/</a>.
//  Also, you can try interactive lessons for CLion by selecting
//  'Help | Learn IDE Features' from the main menu.