shriyanshi24jindal

Number of Ways to Arrive at Destination

Mar 30th, 2026
135
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 15.70 KB | None | 0 0
  1. class Pair
  2. {
  3. int node;
  4. long dist;
  5. Pair(int node, long dist)
  6. {
  7. this.node = node;
  8. this.dist = dist;
  9. }
  10. }
  11. class iPair
  12. {
  13. int vertex;
  14. int weight;
  15. iPair(int vertex, int weight)
  16. {
  17. this.vertex = vertex;
  18. this.weight = weight;
  19. }
  20. }
  21.  
  22. class Solution {
  23. /**
  24.   Build adjacency list from the edge list.
  25.   Use Dijkstra to find shortest distances from node 0 to all nodes
  26.   Maintain a ways[] array:
  27.   ways[u] = number of shortest paths to node u.
  28.   If a new shorter path is found, update distance and ways.
  29.   If an equal distance is found, add ways.
  30.   Return ways[V-1] → number of shortest paths to last node.
  31.   */
  32. public int countPaths(int V, int[][] roads) {
  33. int MOD = 1_000_000_007;
  34.  
  35. // Step-1 Create an adjacency list
  36. ArrayList<ArrayList<iPair>> adj = new ArrayList<>();
  37. for(int i=0; i<V; i++)
  38. {
  39. adj.add(new ArrayList<iPair>());
  40. }
  41.  
  42. for(int[] edge : roads)
  43. {
  44. int u = edge[0];
  45. int v = edge[1];
  46. int w = edge[2];
  47.  
  48. adj.get(u).add(new iPair(v, w));
  49. adj.get(v).add(new iPair(u, w));
  50. }
  51.  
  52. // Step-2 Create a distance array and count ways array
  53. long[] distance = new long[V];
  54. int[] ways = new int[V];
  55. Arrays.fill(distance, Long.MAX_VALUE);
  56. // starting node is 0 so distance will be 0 and no of ways to reach from node 0-> node 0 is 1
  57. distance[0] = 0;
  58. ways[0] = 1;
  59.  
  60. // Step-3 Define Priority queue to store the nodes according to shortest distance
  61. PriorityQueue<Pair> pq = new PriorityQueue<>( (x,y) -> Long.compare(x.dist, y.dist));
  62. pq.add(new Pair(0, 0));
  63.  
  64. while(!pq.isEmpty())
  65. {
  66. Pair pair = pq.poll();
  67. int currentNode = pair.node;
  68. long currentDist = pair.dist;
  69.  
  70. // stale entry
  71. if(currentDist > distance[currentNode])
  72. continue;
  73.  
  74. for(iPair adjNode : adj.get(currentNode))
  75. {
  76. int vertex = adjNode.vertex;
  77. int weight = adjNode.weight;
  78.  
  79. if(distance[vertex] > currentDist + weight)
  80. {
  81. distance[vertex] = currentDist + weight;
  82. pq.offer(new Pair(vertex, distance[vertex]));
  83. ways[vertex] = ways[currentNode];
  84. }
  85. else if(distance[vertex] == currentDist + weight)
  86. {
  87. ways[vertex] = (ways[vertex]+ways[currentNode]) % MOD;
  88. }
  89. }
  90. }
  91. return ways[V-1];
  92. }
  93. }
RAW Paste Data Copied