Cod sursa(job #2780713)

Utilizator DianaIfrosaIfrosa Diana DianaIfrosa Data 7 octombrie 2021 19:01:05
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>

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

class graf
{
    int n;
    const static int nmaxim=100001;
    int m;
    int s;
    vector<int> muchii[nmaxim];

public:
    void BFS();
    void citire();

};


void graf::BFS()
{
    int dist[n+1];
    int viz[n+1];

    queue<int> coada;

    for(int i=1;i<=n;++i)
        dist[i]=-1, viz[i]=0;

    viz[s]=1;
    dist[s]=0;
    coada.push(s);

    while(!coada.empty())
    {
        int vf=coada.front();
        coada.pop();
        for(int i=0; i<muchii[vf].size(); ++i)
            if(!viz[muchii[vf][i]])
            {
                viz[muchii[vf][i]]=1;
                dist[muchii[vf][i]]=dist[vf]+1;
                coada.push(muchii[vf][i]);
            }

    }

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


}
void graf::citire()
{
    int n1,n2;
    fin>>n>>m>>s;
    for(int i=0; i<m; ++i)
    {
        fin>>n1>>n2;
        muchii[n1].push_back(n2);
    }
}
int main()
{
    graf g;
    g.citire();
    g.BFS();


    return 0;
}