Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created June 7, 2026 07:50
Show Gist options
  • Select an option

  • Save thinkphp/50089048fe48acee94b0ea23f71e033b to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/50089048fe48acee94b0ea23f71e033b to your computer and use it in GitHub Desktop.
Parcurgere in latime - graful este reprezentat prin matricea de adiacenta
//BFS > graful este reprezentat prin matricea de adiacenta
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class GrafMatrice {
private:
vector<vector<int>> mat;
vector<bool> vizitat;
int n;
public:
GrafMatrice(int n): n(n), mat(n, vector<int>(n)), vizitat(n, false) {}
void citeste() {
freopen("graf.in", "r", stdin);
cout<<"Introduceti matricea de adiacenta:";
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
cin>>mat[i][j];
}
}
}
void BFS(int start) {
queue<int> coada;
vizitat[ start ] = true;
coada.push( start );
while(!coada.empty()) {
int nod = coada.front();
coada.pop();
cout<<(nod) << " ";
for(int vecin = 0; vecin < n; ++vecin) {
if(mat[nod][vecin] == 1 && !vizitat[vecin]) {
vizitat[vecin] = true;
coada.push(vecin);
}
}
}
}
bool esteVizitat(int i) {return vizitat[i];}
int getN() {return n;}
};
int main(int argc, char const *argv[]) {
freopen("graf.in", "r", stdin);
int n;
cout<<"Numarul de noduri:";
cin>>n;
GrafMatrice g( n );
cout<<"Parcurgere BFS: ";
for(int i = 0; i < n; ++i) {
if(!g.esteVizitat(i)) {
g.BFS(i);
}
}
cout<<endl;
return 0;
}
/*
Input
6
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 1
0 0 0 1 1 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment