Cod sursa(job #3344395)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 1 martie 2026 22:17:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 100005;
vector<int> dist, graph[MAX];

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

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

        for (int next : graph[node])
            if (!dist[next])
            {
                dist[next] = dist[node]+1;
                q.push(next);
            }
    }
}

int main()
{
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    int n, m, s;
    fin >> n >> m >> s;
    dist.assign(n+1, 0);

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

    bfs(s);
    for (int i = 1; i <= n; ++i)
        fout << dist[i]-1 << " ";

    return 0;
}