Approach
Breadth-first search
For Minimum Cost of a Path With Special Roads, 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
- 58 lines of Java from the credited upstream file 2662.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 minimumCost(int[] start, int[] target, int[][] specialRoads) {3 return dijkstra(specialRoads, start[0], start[1], target[0], target[1]);4 }5 6 private int dijkstra(int[][] specialRoads, int srcX, int srcY, int dstX, int dstY) {7 final int n = specialRoads.length;8 9 10 int[] dist = new int[n];11 Arrays.fill(dist, Integer.MAX_VALUE);12 13 Queue<Pair<Integer, Integer>> minHeap =14 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));15 16 17 for (int u = 0; u < n; ++u) {18 final int x1 = specialRoads[u][0];19 final int y1 = specialRoads[u][1];20 final int cost = specialRoads[u][4];21 final int d = Math.abs(x1 - srcX) + Math.abs(y1 - srcY) + cost;22 dist[u] = d;23 minHeap.offer(new Pair<>(dist[u], u));24 }25 26 while (!minHeap.isEmpty()) {27 final int d = minHeap.peek().getKey();28 final int u = minHeap.poll().getValue();29 if (d > dist[u])30 continue;31 final int ux2 = specialRoads[u][2];32 final int uy2 = specialRoads[u][3];33 for (int v = 0; v < n; ++v) {34 if (v == u)35 continue;36 final int vx1 = specialRoads[v][0];37 final int vy1 = specialRoads[v][1];38 final int vcost = specialRoads[v][4];39 40 final int newDist = d + Math.abs(vx1 - ux2) + Math.abs(vy1 - uy2) + vcost;41 if (newDist < dist[v]) {42 dist[v] = newDist;43 minHeap.offer(new Pair<>(dist[v], v));44 }45 }46 }47 48 int ans = Math.abs(dstX - srcX) + Math.abs(dstY - srcY);49 for (int u = 0; u < n; ++u) {50 final int x2 = specialRoads[u][2];51 final int y2 = specialRoads[u][3];52 53 ans = Math.min(ans, dist[u] + Math.abs(dstX - x2) + Math.abs(dstY - y2));54 }55 return ans;56 }57}58