Cod sursa(job #3145831)

Utilizator tudtentiu28Tudor Tentiu tudtentiu28 Data 17 august 2023 11:05:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int NMAX = 1e5 + 2;
const int INF = 1e9;

vector<int> adj[NMAX];
bool viz[NMAX];
int dist[NMAX];

void dfs(int nod)
{
    viz[nod] = 1;
    for (auto& to : adj[nod])
    {
        if (!viz[to]) {
            dfs(to);
        }
    }
}

void bfs(int source)
{
    queue<int> q;
    q.push(source);
    dist[source] = 0;
    viz[source] = 1;

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

        for (auto& to : adj[nod])
        {
            if (!viz[to]) {
                viz[to] = 1;
                dist[to] = dist[nod] + 1;
                q.push(to);
            }
        }
    }
}

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    int n , m; cin >> n >> m;
    int s; cin >> s;
    for (int i = 1; i <= m; i++)
    {
        int x, y; cin >> x >> y;
        adj[x].push_back(y);
    }

    for (int i = 1; i <= n; i++)
    {
        dist[i] = -1;
    }

    bfs(s);

    for (int nod = 1; nod <= n; nod++)
    {
        cout << dist[nod] << ' ';
    }
    cout << '\n';

}