Approach
Breadth-first search
For Find Shortest Path with K Hops, 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
- 56 lines of Java from the credited upstream file 2714.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 3 public int shortestPathWithHops(int n, int[][] edges, int s, int d, int k) {4 List<Pair<Integer, Integer>>[] graph = new List[n];5 6 for (int i = 0; i < n; i++)7 graph[i] = new ArrayList<>();8 9 for (int[] edge : edges) {10 final int u = edge[0];11 final int v = edge[1];12 final int w = edge[2];13 graph[u].add(new Pair<>(v, w));14 graph[v].add(new Pair<>(u, w));15 }16 17 return dijkstra(graph, s, d, k);18 }19 20 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int k) {21 int[][] dist = new int[graph.length][k + 1];22 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));23 24 dist[src][k] = 0;25 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {26 { offer(new int[] {dist[src][k], src, k}); } 27 };28 29 while (!minHeap.isEmpty()) {30 final int d = minHeap.peek()[0];31 final int u = minHeap.peek()[1];32 final int hops = minHeap.poll()[2];33 if (u == dst)34 return d;35 if (dist[u][hops] > d)36 continue;37 for (Pair<Integer, Integer> pair : graph[u]) {38 final int v = pair.getKey();39 final int w = pair.getValue();40 41 if (d + w < dist[v][hops]) {42 dist[v][hops] = d + w;43 minHeap.offer(new int[] {dist[v][hops], v, hops});44 }45 46 if (hops > 0 && d < dist[v][hops - 1]) {47 dist[v][hops - 1] = d;48 minHeap.offer(new int[] {dist[v][hops - 1], v, hops - 1});49 }50 }51 }52 53 throw new IllegalArgumentException();54 }55}56