vitormartinotti

bfs

Oct 2nd, 2025 (edited)
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<int> grafo[MAXN];
  6.  
  7. int marc[MAXN], dist[MAXN];
  8.  
  9. void bfs(int s){
  10.     queue<int> q;
  11.     q.push(s);
  12.     marc[s] = 1;
  13.     dist[s] = 0;
  14.     pai[s] = -1;
  15.  
  16.     while(!q.empty()){
  17.         int v = q.front();
  18.         q.pop();
  19.         for(auto viz : grafo[v]){
  20.             if(marc[viz] == 0){
  21.                 q.push(viz);
  22.                 marc[viz] = 1;
  23.                 dist[viz] = dist[v]+1;
  24.                 pai[viz] = v;
  25.             }
  26.         }
  27.     }
  28. }
  29.  
  30. int main(){
  31.    
  32.     //recuperando o menor caminho do n até a fonte
  33.     vector<int> path;
  34.     while(pai[n] != -1){
  35.         path.push_back(n);
  36.         n = pai[n];
  37.     }
  38.     path.push_back(n);
  39.     reverse(path.begin(),path.end());
  40.    
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment