shriyanshi24jindal

Shortest Path in an Undirected Graph

Mar 29th, 2026
9
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 16.07 KB | None | 0 0
  1. class iPair{
  2. int first, second;
  3. public iPair(int first, int second)
  4. {
  5. this.first = first;
  6. this.second = second;
  7. }
  8. }
  9.  
  10. class Pair
  11. {
  12. int distance, node;
  13. public Pair(int distance, int node)
  14. {
  15. this.distance = distance;
  16. this.node = node;
  17. }
  18. }
  19.  
  20. class Solution {
  21. public List<Integer> shortestPath(int n, int m, int edges[][]) {
  22.  
  23. // Step-1 create an adjacency list
  24. ArrayList<ArrayList<iPair>> adj = new ArrayList<>();
  25. for(int i=0;i<=n;i++)
  26. {
  27. adj.add(new ArrayList<iPair>());
  28. }
  29.  
  30. for(int[] edge : edges)
  31. {
  32. int u = edge[0];
  33. int v = edge[1];
  34. int w = edge[2];
  35. adj.get(u).add(new iPair(v,w));
  36. adj.get(v).add(new iPair(u, w));
  37. }
  38.  
  39. // Step-2 Create a distance array and parent node array
  40. int[] distance = new int[n+1];
  41. int[] parent = new int[n+1];
  42. for(int i=0;i<=n;i++)
  43. {
  44. distance[i] = (int)1e9;
  45. parent[i] = i;
  46. }
  47. distance[1] = 0;
  48.  
  49. // Step-3 Store the nodes into MIN-HEAP accoriding to node's weight
  50. PriorityQueue<Pair> pq = new PriorityQueue<Pair>((x,y) -> Integer.compare(x.distance, y.distance));
  51. pq.add(new Pair(0, 1));
  52.  
  53. // Step-4 Traverse the nodes present in min-heap
  54. while(pq.size()!=0)
  55. {
  56. Pair pair = pq.poll();
  57. int currentNode = pair.node;
  58. int currentDist = pair.distance;
  59.  
  60. for(iPair neighbour : adj.get(currentNode))
  61. {
  62. int adjNode = neighbour.first;
  63. int weight = neighbour.second;
  64.  
  65. if(distance[adjNode] > (currentDist + weight))
  66. {
  67. distance[adjNode] = currentDist + weight;
  68. pq.add(new Pair(distance[adjNode], adjNode));
  69. parent[adjNode] = currentNode;
  70. }
  71. }
  72. }
  73.  
  74. List<Integer> arr = new ArrayList<>();
  75. if(distance[n] == 1e9)
  76. {
  77. arr.add(-1);
  78. return arr;
  79. }
  80.  
  81. int node = n;
  82. while(parent[node] != node)
  83. {
  84. arr.add(node);
  85. node = parent[node];
  86. }
  87.  
  88. arr.add(1);
  89. arr.add(distance[n]);
  90.  
  91. Collections.reverse(arr);
  92. return arr;
  93. }
  94. }
RAW Paste Data Copied