Approach
Breadth-first search
For Number of Ways to Arrive at Destination, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 55 lines of Java from the credited upstream file 1976.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int countPaths(int n, int[][] roads) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 5 for (int i = 0; i < n; i++)6 graph[i] = new ArrayList<>();7 8 for (int[] road : roads) {9 final int u = road[0];10 final int v = road[1];11 final int w = road[2];12 graph[u].add(new Pair<>(v, w));13 graph[v].add(new Pair<>(u, w));14 }15 16 return dijkstra(graph, 0, n - 1);17 }18 19 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) {20 final int MOD = 1_000_000_007;21 long[] ways = new long[graph.length];22 Arrays.fill(ways, 0);23 long[] dist = new long[graph.length];24 Arrays.fill(dist, Long.MAX_VALUE);25 26 ways[src] = 1;27 dist[src] = 0;28 Queue<Pair<Long, Integer>> minHeap =29 new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {30 { offer(new Pair<>(dist[src], src)); }31 };32 33 while (!minHeap.isEmpty()) {34 final long d = minHeap.peek().getKey();35 final int u = minHeap.poll().getValue();36 if (d > dist[u])37 continue;38 for (Pair<Integer, Integer> pair : graph[u]) {39 final int v = pair.getKey();40 final int w = pair.getValue();41 if (d + w < dist[v]) {42 dist[v] = d + w;43 ways[v] = ways[u];44 minHeap.offer(new Pair<>(dist[v], v));45 } else if (d + w == dist[v]) {46 ways[v] += ways[u];47 ways[v] %= MOD;48 }49 }50 }51 52 return (int) ways[dst];53 }54}55