Cod sursa(job #3220124)

Utilizator Bogdan345Marius Mihalache Bogdan345 Data 2 aprilie 2024 15:30:00
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");
vector<int>distanta;
vector<vector<int>>gr;
const int inf=1e5+1;
struct Coada{
    int val;
    Coada *next;
};
void push(Coada* &S,Coada* &F,const int&nr){
    Coada *x=new Coada;
    x->val=nr;
    x->next=NULL;
    if(S!=NULL){
        F->next=x;
        F=x;
    }else{
    S=x;
    F=S;
    }
}
void pop(Coada* &S){
    if(S!=NULL){
     Coada *x=S;
     S=S->next;
     delete x;
    }
}
int front(Coada* S){
    if(S!=NULL){
        return S->val;
    }else{
        return -1;
}
}
bool empty(Coada*S){
    return S==NULL;
}
void bfs(int nod){
    Coada *S=NULL,*F=NULL;
    distanta[nod]=0;
    push(S,F,nod);
    while(!empty(S)){
        int nod_curent=front(S);
        pop(S);
        for(const auto&x:gr[nod_curent]){
            if(distanta[x]==inf){
                distanta[x]=distanta[nod_curent]+1;
                push(S,F,x);
            }
        }
    }
}
int main(){
    int n,m,nod;
    cin>>n>>m>>nod;
    gr.resize(n+1);
    distanta.resize(n+1,inf);
    int a,b;
    for(int i=1;i<=m;i++){
        cin>>a>>b;
        gr[a].push_back(b);
    }
    for(int i=1;i<=n;i++){
        distanta[i]=inf;
    }
    bfs(nod);
    for(int i=1;i<=n;i++){
        if(distanta[i]==inf){
        cout<<-1<<" ";
    }else{
        cout<<distanta[i]<<" ";
    }
}
}