Cod sursa(job #3316905)

Utilizator gpl12Giulia gpl12 Data 21 octombrie 2025 13:34:00
Problema BFS - Parcurgere in latime Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;

int n, m, cnt=0, s, d[10000];
int viz[1000];
vector<int> l[1000];
// struct nod {
//     int x;
//     nod *a;
// } ;
// nod* v[1000];


// void add(nod* &dest, int val){
//     nod* p=new nod;
//     p=new nod;
//     p->x=val;
//     p->a=dest;
//     dest=p;
//
// }
//
// void citire(){
//     ifstream fin("dfs.in" );
//     fin>>n>>m;
//     int x, y;
//     for (int i=1; i<=m; i++) {
//         fin>>x>>y;
//         add(v[x], y);
//         add(v[y], x);
//     }
//
// }
// void DFS(int nod) {
//     viz[nod]=1;
//     for (nod* p=v[nod]; p!=NULL; p=p->a) {
//         if (!viz[p->x]) DFS(p->x);
//     }
// }

void BFS(int s) {
    int x,i;
    queue<int> q;
    q.push(s);
    viz[s]=1;
    d[s]=0;

    while (q.size()>0) {
        x=q.front();
        q.pop();
        for (i=0; i<l[x].size(); i++ ) {
            int y=l[x][i];
            if (viz[y]==0) {
                q.push(y);
                viz[y]=1;
                d[y]=d[x]+1;
            }
        }

    }

}
void citire2() {
    ifstream fin("bfs.in");
    fin>>n>>m>>s;
    int x,y;
    for (int i=1; i<=m; i++) {
        fin>>x>>y;
        l[x].push_back(y);
    }
    fin.close();
}
// TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
int main() {

citire2();
    for (int i=1; i<=n; i++) {
        d[i]=-1;
    }
    BFS(s);
    ofstream fout("bfs.out");
    for(int i = 1; i <= n; i++) {
        fout << d[i] << " ";
    }
    fout.close();

    return 0;
}



// TIP See CLion help at <a
// href="https://www.jetbrains.com/help/clion/">jetbrains.com/help/clion/</a>.
//  Also, you can try interactive lessons for CLion by selecting
//  'Help | Learn IDE Features' from the main menu.