Cod sursa(job #3156456)

Utilizator darius1843Darius Suditu darius1843 Data 11 octombrie 2023 17:17:16
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>

using namespace std;

ifstream in("dfs.in");
ofstream out("dfs.out");

const int NMAX = 1e5;
vector<int> G[NMAX + 1];
int d[NMAX + 1];
int vis[NMAX + 1];

void BFS(int x) {
    queue<int> q;
    q.push(x);
    d[x] = 0;
    vis[x] = 1;
    while (!q.empty()) {
        x = q.front();
        q.pop();
        for (auto next : G[x])
        {
            if (!vis[next])
            {
                q.push(next);
                vis[next] = 1;
                d[next] = d[x] + 1;
            }
        }
    }
    return;
}

int main()
{
    int n, m, v;
    in >> n >> m >> v;
    int x, y;
    for (int i = 1; i <= m; i++)
    {
        in >> x >> y;
        G[x].push_back(y);
    }
    BFS(v);
    for (int i = 1; i <= n; i++) {
        if (i != v && d[i] == 0)
            out << "-1 ";
        else
            out << d[i] << " ";
    }

    return 0;
}