Cod sursa(job #3214263)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 13 martie 2024 23:06:12
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>
#include <queue>
#define MAX 100000
using namespace std;
ifstream cin ("bfs.in");
ofstream cout ("bfs.out");
int dist[MAX + 10];
vector <int> graph[MAX + 10];
queue <int> q;
int main()
{
    int n, m, s;
    cin >> n >> m >> s;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        graph[x].push_back(y);
    }
    q.push(s);
    dist[s] = 1;
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        for (const auto &next : graph[node])
            if (dist[next] == 0)
            {
                q.push(next);
                dist[next] = dist[node] + 1;
            }
    }
    for (int i = 1; i <= n; i++)
        cout << dist[i] - 1 << ' ';
    return 0;
}