Cod sursa(job #2796654)

Utilizator Irina.comanIrina Coman Irina.coman Data 8 noiembrie 2021 16:53:40
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
vector<int> graph[100005];
queue<int> q;
int vis[100005], nod, d[100005];
void bfs(int node)
{
    q.push(node);
    vis[node] = true;
    while(!q.empty())
    {
        node = q.front();
        q.pop();
        for (int i = 0; i < graph[node].size(); i++)
        {
            int next = graph[node][i];
            if (!vis[next] and d[next] != 0)
            {
                d[next] = d[node] + 1;
                q.push(next);
                vis[next] = true;
            }
        }
    }
}


int main()
{
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    int n, m, s, x, y;
    fin >> n >> m >> s;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        graph[x].push_back(y);
    }
    d[s] = 0;
    bfs(s);
    for (int i = 1; i <= n; i++)
        if (!vis[i])
            d[i] = -1;
    for (int i = 1; i <= n; i++)
        fout << d[i] << " ";
    return 0;
}