Cod sursa(job #3376777)

Utilizator biancagravaGRAVA Bianca biancagrava Data 19 noiembrie 2026 17:19:57
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
//
// Created by Bianca Grava on 19/11/2026.
//
#include<fstream>
#include<iostream>
#include<queue>
#include<vector>

using namespace std;

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

int main() {
    int n,m,a,b,curr,s;
    in>>n>>m>>s;
    vector<vector<int>> adj(n+1);
    queue<int> q;
    vector<int> lengths(n+1,-1);
    vector<bool> visited(n+1,false);
    for (int i=0;i<m;i++) {
        in>>a>>b;
        adj[a].push_back(b);
    }
    //we'll consider s our root since that is the node from which we'll traverese with bfs
    q.push(s);
    lengths[s]=0;
    while(!q.empty()) {
        curr=q.front();
        q.pop();
        if (!visited[curr]) {
            visited[curr]=true;
            for (int elem: adj[curr]) {
                if (!visited[elem]) {
                    q.push(elem);
                    lengths[elem]=lengths[curr]+1;
                }
            }
        }
    }
    for (int i=1;i<=n;i++)
        out<<lengths[i]<<" ";
    return 0;
}