Beingamanforever

Number of shortest paths from any particular node to all nodes using bFS

Dec 30th, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 KB | None | 0 0
  1. auto bfs(int s)
  2. {
  3.     vi dist(n + 1, INF), paths(n + 1, 0);
  4.     dist[s] = 0;
  5.     paths[s] = 1;
  6.     queue<int> q;
  7.     q.push(s);
  8.     while (!q.empty())
  9.     {
  10.         int u = q.front();
  11.         q.pop();
  12.         for (int v : adj[u])
  13.         {
  14.             if (dist[v] > dist[u] + 1)
  15.             {
  16.                 dist[v] = dist[u] + 1;
  17.                 paths[v] = paths[u];
  18.                 q.push(v);
  19.             }
  20.             else if (dist[v] == dist[u] + 1)
  21.             {
  22.                 paths[v] += paths[u];
  23.             }
  24.         }
  25.     }
  26.     return make_pair(dist, paths);
  27. }
  28.  
Advertisement
Add Comment
Please, Sign In to add comment