Cod sursa(job #2330940)

Utilizator laviniadragneDragne Lavinia laviniadragne Data 28 ianuarie 2019 23:33:31
Problema BFS - Parcurgere in latime Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>

using namespace std;

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

queue <int> q;
vector <int> graph[101];
int viz[101], dist[101];
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 or i==s) gout << dist[i] - 1 << " ";
          else gout << -1 << " ";
        }

    return 0;
}