Approach
Breadth-first search
For Cheapest Flights Within K Stops, 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
- 48 lines of Java from the credited upstream file 787.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 findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {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[] flight : flights) {9 final int u = flight[0];10 final int v = flight[1];11 final int w = flight[2];12 graph[u].add(new Pair<>(v, w));13 }14 15 return dijkstra(graph, src, dst, k);16 }17 18 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int k) {19 int[][] dist = new int[graph.length][k + 2];20 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));21 22 dist[src][k + 1] = 0;23 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {24 { offer(new int[] {dist[src][k + 1], src, k + 1}); } 25 };26 27 while (!minHeap.isEmpty()) {28 final int d = minHeap.peek()[0];29 final int u = minHeap.peek()[1];30 final int stops = minHeap.poll()[2];31 if (u == dst)32 return d;33 if (stops == 0 || d > dist[u][stops])34 continue;35 for (Pair<Integer, Integer> pair : graph[u]) {36 final int v = pair.getKey();37 final int w = pair.getValue();38 if (d + w < dist[v][stops - 1]) {39 dist[v][stops - 1] = d + w;40 minHeap.offer(new int[] {dist[v][stops - 1], v, stops - 1});41 }42 }43 }44 45 return -1;46 }47}48