Cod sursa(job #2808508)

Utilizator CristeaCristianCristea Cristian CristeaCristian Data 25 noiembrie 2021 11:17:39
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <queue>
#include <algorithm>
#include <vector>

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector <vector <int> > v;
vector < int > viz;
const int INF = 1000000;
void bfs(int s)
{
    queue <int> q;
    q.push(s);
    viz[s] = 0;
    int fr;
    while(!q.empty())
    {
        fr = q.front();
        q.pop();
        for(int i = 0; i < v[fr].size(); i++)
        {
            if(viz[v[fr][i]] > viz[fr] + 1)
            {
                viz[v[fr][i]] = viz[fr] + 1;
                q.push(v[fr][i]);
            }
        }
    }
}
int main()
{
    int n, m, s, i, a, b;
    fin >> n >> m >> s;
    v.resize(n);
    viz.resize(n);
    for(i = 0; i < n; i++)
        viz[i] = INF;
    for(i = 1; i <= m; i++)
    {
        fin >> a >> b;
        a--;
        b--;
        v[a].push_back(b);
    }
    bfs(s-1);
    for(i = 0; i < n; i++)
    {
        if(viz[i] == INF)
            fout << "-1 ";
        else
            fout << viz[i] << ' ';
    }
    return 0;
}