Cod sursa(job #2960587)

Utilizator CiuiGinjoveanu Dragos Ciui Data 4 ianuarie 2023 18:29:42
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;

const int MAX_SIZE = 100001;
int n, m, s;
deque<int> nodes, neighbors[MAX_SIZE];
vector<int> cost;

void graph_traversal(int node) {
    for (int i = 0; i <= n; ++i) {
        cost.push_back(-1);
    }
    cost[node] = 0;
    nodes.push_back(node);
    while (!nodes.empty()) {
        int curr_node = nodes.front();
        nodes.pop_front();
        for (auto i = neighbors[curr_node].begin(); i != neighbors[curr_node].end(); ++i) {
            if (cost[*i] == -1) {
                cout << *i << endl;
                nodes.push_back(*i);
                cost[*i] = cost[curr_node] + 1;
            }
        }
    }
}

int main() {
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    fin >> n >> m >> s;
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        neighbors[x].push_back(y);
    }
    graph_traversal(s);
    for (int i = 1; i <= n; ++i) {
        fout << cost[i] << ' ';
    }
    return 0;
}