Cod sursa(job #3368393)

Utilizator teogrecigrecioiu teo teogreci Data 14 octombrie 2026 13:17:58
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int INF = -1;

int n, m, startNode;
vector<vector<int>> graph;
vector<int> dist;

void bfs(int start)
{
    queue<int> q;

    dist[start] = 0;
    q.push(start);

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

        for (int neighbor : graph[currentNode])
        {
            if (dist[neighbor] == INF)
            {
                dist[neighbor] = dist[currentNode] + 1;
                q.push(neighbor);
            }
        }
    }
}

int main()
{
    fin >> n >> m >> startNode;

    graph.resize(n + 1);
    dist.resize(n + 1, INF);

    for (int i = 0; i < m; i++)
    {
        int u, v;
        fin >> u >> v;
        graph[u].push_back(v);
    }

    bfs(startNode);

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

    return 0;
}