Cod sursa(job #1639307)

Utilizator IoanaPPascu Ioana IoanaP Data 8 martie 2016 11:44:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

int n, m, i, x, y, s;
vector <vector <int> > graph;
vector <int> viz;
ifstream f ("bfs.in");
ofstream g ("bfs.out");

void BFS (int vertex){
    int i;
    if (vertex < 0 || vertex > n-1) return;
    queue <int> q;
    int elem;
    q.push (vertex);
    viz[vertex] = 0;
    while (!q.empty()) {
        elem = q.front();
        for (i = 0; i < graph[elem].size(); i++)
           if (viz[graph[elem][i]] == -1) {
                q.push (graph[elem][i]);
                //cout << graph[elem][i] + 1 << " ";
                viz [graph[elem][i]] = viz[elem] + 1;
           }
        q.pop();
        }
    for (i = 0; i < n; i++) g << viz[i] << " ";
}

int main()
{
    f >> n >> m >> s;
    graph.resize(n);
    viz.resize(n, -1);
    for (i = 0; i < m; i++)
    {
        f >> x >> y;
        x--; y--;
        graph[x].push_back(y);
    }
    s--;
    BFS (s);
    f.close();
    g.close();
    return 0;
}