Cod sursa(job #2935513)

Utilizator _Lucas_Iftinca Lucas _Lucas_ Data 6 noiembrie 2022 20:03:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

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

vector<int> G[100001];
queue<int> q;
int path[100001];
int n, m, s;

int main()
{
    fin >> n >> m >> s;
    for (int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    for (int i = 1; i <= n; i++)
        path[i] = -1;
    path[s] = 0;
    q.push(s);
    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        for (auto it : G[nod]) {
            if (path[it] == -1) {
                path[it] = path[nod] + 1;
                q.push(it);
            }
        }
    }
    for (int i = 1; i <= n; i++)
        fout << path[i] << ' ';
    return 0;
}