Cod sursa(job #1981888)

Utilizator Dragne.Andrei11Dragne Andrei Dragne.Andrei11 Data 17 mai 2017 09:34:03
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;
const int MAX_N = 100005;

vector<int> graph[MAX_N];
int dist[MAX_N];
bool visited[MAX_N];

void bfs(int startNode)
{
    dist[startNode] = 0;
    queue<int> bfsQueue;
    bfsQueue.push(startNode);
    visited[startNode] = true;
    while (!bfsQueue.empty())
    {
        int currentNode = bfsQueue.front();
        bfsQueue.pop();
        for (auto neighbour: graph[currentNode])
        {
            if (!visited[neighbour])
            {
                visited[neighbour] = true;
                dist[neighbour] = dist[currentNode] + 1;
                bfsQueue.push(neighbour);
            }
        }
    }
}

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

    int N, M, v, x, y;
    scanf("%d%d", &N, &M, &v);
    for (int i = 1; i <= M; i += 1)
    {
        scanf("%d%d", &x, &y);
        graph[x].push_back(y);
    }
    bfs(v);
    for (int i = 1; i <= N; i += 1)
        printf("%d ", dist[i]);
    printf("\n");

    return 0;
}