Cod sursa(job #3165037)

Utilizator hvbitsvtAndreea Grosu hvbitsvt Data 5 noiembrie 2023 11:46:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>

using namespace std;

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

int n, m, s;
vector<list<int>> liste(100001);

void memorareListe(bool orientat)
{
    fin >> n >> m >> s;

    int x, y;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        liste[x].push_back(y);
        if (!orientat) liste[y].push_back(x);
    }
}

void BFS(int start)
{
    int vis[100001] = {0};
    int d[100001];
    for (int i = 1; i <= n; i++)
        d[i] = -1;
    queue<int> q;
    q.push(start);
    d[start] = 0;
    vis[start] = 1;

    int x;
    while (!q.empty())
    {
        x = q.front();
        q.pop();

        for (auto next:liste[x])
        {
            if (!vis[next])
            {
                q.push(next);
                vis[next] = 1;
                d[next] = d[x] + 1;
            }
        }
    }

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

int main()
{
    bool orientat = true;

    memorareListe(orientat);
    BFS(s);
    return 0;
}