Cod sursa(job #3275914)

Utilizator TonyyAntonie Danoiu Tonyy Data 11 februarie 2025 22:18:31
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
using namespace std;

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

const int Max = 1e5 + 1;
vector<int> graph[Max], d(Max, -1);

void bfs(int node)
{
    queue<int> q;
    q.push(node);
    d[node] = 0;
    while(!q.empty())
    {
        node = q.front();
        q.pop();
        for(int i: graph[node])
        {
            if(d[i] == -1)
            {
                d[i] = d[node] + 1;
                q.push(i);
            }
        }
    }
}

int main()
{
    int n, m, s;
    fin >> n >> m >> s;
    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 << d[i] << " ";
    
    fin.close();
    fout.close();
    return 0;
}