Cod sursa(job #3290390)

Utilizator Horia14Horia Banciu Horia14 Data 30 martie 2025 16:41:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>

#define MAX_VERTICES 100000
using namespace std;

vector<int> g[MAX_VERTICES + 1];
int dist[MAX_VERTICES + 1];
queue<int> q;
int n, m, source;

void readGraph(string fileName) {
    int x, y;
    ifstream fin(fileName);
    fin >> n >> m >> source;
    // cout << n << " " << m << " " << source << " " << "\n";

    for (int i = 1; i <= m; ++i) {
        fin >> x >> y;
        g[x].push_back(y);
        // cout << x << " " << y << "\n";
    }

    fin.close();
}

void BFS(int src) {

    int currNode;

    for (int i = 0; i <= n; ++i) {
        dist[i] = -1;
    }

    dist[src] = 0;

    q.push(src);

    while (!q.empty()) {

        currNode = q.front();
        q.pop();

        for (auto neighbour : g[currNode]) {
            if (dist[neighbour] == -1) {
                dist[neighbour] = dist[currNode] + 1;
                q.push(neighbour);
            }
        }
    }
}

void printDistances(string fileName) {
    ofstream fout(fileName);

    for (int i = 1; i <= n; ++i) {
        fout << dist[i] << " ";
    }

    fout << "\n";

    fout.close();
}

int main() {
    readGraph("bfs.in");
    BFS(source);
    printDistances("bfs.out");

    return 0;
}