Approach
Breadth-first search
For Minimum Cost to Reach Destination in Time, 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
- 59 lines of Java from the credited upstream file 1928.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 minCost(int maxTime, int[][] edges, int[] passingFees) {3 final int n = passingFees.length;4 List<Pair<Integer, Integer>>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] edge : edges) {8 final int u = edge[0];9 final int v = edge[1];10 final int t = edge[2];11 graph[u].add(new Pair<>(v, t));12 graph[v].add(new Pair<>(u, t));13 }14 15 return dijkstra(graph, 0, n - 1, maxTime, passingFees);16 }17 18 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int maxTime,19 int[] passingFees) {20 int[] cost = new int[graph.length]; 21 int[] dist = new int[graph.length]; 22 Arrays.fill(cost, Integer.MAX_VALUE);23 Arrays.fill(dist, maxTime + 1);24 25 cost[0] = passingFees[0];26 dist[0] = 0;27 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {28 { offer(new int[] {cost[src], dist[src], src}); } 29 };30 31 while (!minHeap.isEmpty()) {32 final int currCost = minHeap.peek()[0];33 final int d = minHeap.peek()[1];34 final int u = minHeap.poll()[2];35 if (u == dst)36 return cost[dst];37 if (d > dist[u] && currCost > cost[u])38 continue;39 for (Pair<Integer, Integer> pair : graph[u]) {40 final int v = pair.getKey();41 final int w = pair.getValue();42 if (d + w > maxTime)43 continue;44 45 if (currCost + passingFees[v] < cost[v]) {46 cost[v] = currCost + passingFees[v];47 dist[v] = d + w;48 minHeap.offer(new int[] {cost[v], dist[v], v});49 } else if (d + w < dist[v]) {50 dist[v] = d + w;51 minHeap.offer(new int[] {currCost + passingFees[v], dist[v], v});52 }53 }54 }55 56 return -1;57 }58}59