Problem solution · Java

Minimum Cost of a Path With Special Roads

Minimum Cost of a Path With Special Roads: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
58 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Cost of a Path With Special Roads · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minimumCost(int[] start, int[] target, int[][] specialRoads) {    return dijkstra(specialRoads, start[0], start[1], target[0], target[1]);  }   private int dijkstra(int[][] specialRoads, int srcX, int srcY, int dstX, int dstY) {    final int n = specialRoads.length;    // dist[i] := the minimum distance of (srcX, srcY) to    // specialRoads[i](x2, y2)    int[] dist = new int[n];    Arrays.fill(dist, Integer.MAX_VALUE);    // (d, u), where u := the i-th specialRoads    Queue<Pair<Integer, Integer>> minHeap =        new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));     // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2)    for (int u = 0; u < n; ++u) {      final int x1 = specialRoads[u][0];      final int y1 = specialRoads[u][1];      final int cost = specialRoads[u][4];      final int d = Math.abs(x1 - srcX) + Math.abs(y1 - srcY) + cost;      dist[u] = d;      minHeap.offer(new Pair<>(dist[u], u));    }     while (!minHeap.isEmpty()) {      final int d = minHeap.peek().getKey();      final int u = minHeap.poll().getValue();      if (d > dist[u])        continue;      final int ux2 = specialRoads[u][2];      final int uy2 = specialRoads[u][3];      for (int v = 0; v < n; ++v) {        if (v == u)          continue;        final int vx1 = specialRoads[v][0];        final int vy1 = specialRoads[v][1];        final int vcost = specialRoads[v][4];        // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2)        final int newDist = d + Math.abs(vx1 - ux2) + Math.abs(vy1 - uy2) + vcost;        if (newDist < dist[v]) {          dist[v] = newDist;          minHeap.offer(new Pair<>(dist[v], v));        }      }    }     int ans = Math.abs(dstX - srcX) + Math.abs(dstY - srcY);    for (int u = 0; u < n; ++u) {      final int x2 = specialRoads[u][2];      final int y2 = specialRoads[u][3];      // (srcX, srcY) -> (x2, y2) -> (dstX, dstY).      ans = Math.min(ans, dist[u] + Math.abs(dstX - x2) + Math.abs(dstY - y2));    }    return ans;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗