Cod sursa(job #3164939)

Utilizator hvbitsvtAndreea Grosu hvbitsvt Data 4 noiembrie 2023 20:05:30
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>

using namespace std;

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

int n, m, s;
int v[100][100];

/*
void memorareMatrice(bool orientat)
{
    fin >> n >> m;

    int x, y;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        if (orientat) v[x][y] = 1;
        else
        {
            v[x][y] = 1;
            v[y][x] = 1;
        }
    }
}

void afisareMatrice(int n)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
            cout << v[i][j] << " ";
        cout << '\n';
    }
}*/

vector<list<int>> liste(100);

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 afisareListe(int n)
{
    for (int i = 1; i <= n; i++)
    {
        cout << "Nodul " << i << ": ";
        for (auto vecin : liste[i])
            cout << vecin << " ";
        cout << '\n';
    }
}

void BFS(int start)
{
    int vis[100000] = {0};
    int d[100000];
    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;

    //memorareMatrice(orientat);
    //afisareMatrice(n);

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