Cod sursa(job #3145840)

Utilizator TomaBToma Brihacescu TomaB Data 17 august 2023 11:11:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 1e5 + 2;
const int INF = 1e9;

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

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

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

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

int main(int argc, char const *argv[])
{   
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    int n, m, s;
    cin >> n >> m >> s;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        adj[x].push_back(y);
        // adj[y].push_back(x); fiindca problema descrie un graf orientat
    }

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

    bfs(s);

    for (int nod = 1; nod <= n; nod++)
        cout << dist[nod] << " ";
    return 0;
}