Cod sursa(job #2332768)

Utilizator laviniadragneDragne Lavinia laviniadragne Data 31 ianuarie 2019 11:07:42
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5 + 5;
queue <int> q;
vector <int> graph[NMAX];
int viz[NMAX], dist[NMAX];

void bfs(int start)
{
    q.push(start);
    viz[start] = 1;
    dist[start] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (int j = 0; j < graph[nod].size(); j++)
        {

            if (viz[graph[nod][j]] == 0)
            {
               q.push(graph[nod][j]);
               viz[graph[nod][j]] = 1;
               dist[graph[nod][j]] = dist [nod] + 1;
            }
        }
    }
}


int main()
{
    int i, n, m, x, y, s;

    fin >> n >> m >> s;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y;
        graph[x].push_back(y);
    }
    bfs(s);
    for(i = 1; i <= n; i++)
        if (dist[i] != 0 || i == s) gout << dist[i] - 1 << " ";
        else gout << -1 << " ";


    return 0;
}