Advertisement
Oppenheimer

BFS (with path print)

Aug 19th, 2022
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. /*
  2. BFS : O(E + V) .. shortetst path from source vertetx to another .. (unweighted graph ***)
  3. */
  4. unordered_map<int,vector<int>> adj;  // adjacency list representation
  5. int n; // number of nodes
  6. int s; // source vertex given
  7.  
  8. queue<int> q;
  9. vector<bool> used(n); // visited array
  10. vector<int> d(n), p(n); // d is distance vertex and p is parent vertex ..
  11.  
  12. q.push(s);
  13. used[s] = true;
  14. p[s] = -1; // parent of source vertex is -1
  15.  
  16. while (!q.empty()) {
  17.     int v = q.front();
  18.     q.pop();
  19.     for (int u : adj[v]) {
  20.         if (!used[u]) {
  21.             used[u] = true;
  22.             q.push(u);
  23.             d[u] = d[v] + 1;
  24.             p[u] = v;
  25.         }
  26.     }
  27. }
  28.  
  29. /// printing the shortets path from source to any vertex u ..
  30. if (!used[u]) {
  31.     cout << "No path!";
  32. } else {
  33.     vector<int> path;
  34.     for (int v = u; v != -1; v = p[v])
  35.         path.push_back(v);
  36.    
  37.    
  38.     reverse(path.begin(), path.end());
  39.     cout << "Path: ";
  40.     for (int v : path)
  41.         cout << v << " ";
  42. }
  43.  
  44.  
  45.  
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement