Cod sursa(job #2620318)

Utilizator mex7Alexandru Valentin mex7 Data 28 mai 2020 18:18:48
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<int> lista[100010];
bool freq[100010];

void bfs(int start, int end) {
    queue<pair<int, int> > q;
    q.push(make_pair(start, 0));
    freq[start] = 1;

    while (!q.empty()) {
        pair<int, int> top = q.front();
        q.pop();

        if (top.first == end) {
            cout << top.second << " ";
            return;
        }

        for (int i = 0; i < lista[top.first].size(); i++)
            if (!freq[lista[top.first][i]]) {
                q.push(make_pair(lista[top.first][i], top.second + 1));
                freq[i] = 1;
            }
    }

    cout << -1 << " ";
}

void clear(int n) {
    for (int i = 1; i <= n; i++)
        freq[i] = 0;
}

int main() {
    int n, m, s;
    int x, y;

    cin >> n >> m >> s;
    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        lista[x].push_back(y);
    }

    for (int i = 1; i <= n; i++) {
       bfs(s, i);
       clear(n);
    }

    return 0;
}