dvjsharma

Untitled

Aug 21st, 2025
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> shortestPath(int n, vector<vector<int>>& adj, int src, int dest) {
  5.     vector<int> dist(n, INT_MAX), parent(n, -1);
  6.     queue<int> q;
  7.  
  8.     dist[src] = 0;
  9.     q.push(src);
  10.  
  11.     // BFS
  12.     while (!q.empty()) {
  13.         int u = q.front(); q.pop();
  14.         for (int v : adj[u]) {
  15.             if (dist[v] > dist[u] + 1) {
  16.                 dist[v] = dist[u] + 1;
  17.                 parent[v] = u;
  18.                 q.push(v);
  19.             }
  20.         }
  21.     }
  22.  
  23.     // Reconstruct path from src → dest
  24.     vector<int> path;
  25.     if (dist[dest] == INT_MAX) return path; // no path
  26.    
  27.     for (int v = dest; v != -1; v = parent[v])
  28.         path.push_back(v);
  29.     reverse(path.begin(), path.end());
  30.     return path;
  31. }
  32.  
  33. int main() {
  34.     int n = 6;
  35.     vector<vector<int>> adj = {
  36.         {1,2}, {0,3}, {0,3}, {1,2,4}, {3,5}, {4}
  37.     };
  38.  
  39.     int src = 0, dest = 5;
  40.     vector<int> path = shortestPath(n, adj, src, dest);
  41.  
  42.     cout << "Shortest path from " << src << " to " << dest << ": ";
  43.     for (int v : path) cout << v << " ";
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment