2662. Minimum Cost of a Path With Special Roads
```java
class Solution {
class Step {
int x;
int y;
int cost;
Step(int x, int y, int cost) {
this.x = x;
this.y = y;
this.cost = cost;
}
}
public int minimumCost(int[] start, int[] target, int[][] specialRoads) {
Queue<Step> queue = new PriorityQueue<>((a, b) -> a.cost - b.cost);
queue.offer(new Step(start[0], start[1], 0)); // put start
Set<Pair<Integer, Integer>> visited = new HashSet<>();
while (!queue.isEmpty()) {
Step cur = queue.poll();
if (cur.x == target[0] && cur.y == target[1]) {
return cur.cost;
}
Pair position = new Pair(cur.x, cur.y);
if (visited.contains(position)) {
continue;
}
// key point -> put all kinds of dist to queue, visited record this ending's value
// here every time, we'll update a smaller value in PQ (poll smaller first)
visited.add(position); // dist: current to target
queue.offer(new Step(target[0], target[1], getDist(cur.x, cur.y, target[0], target[1]) + cur.cost));
for (int[] sp : specialRoads) { // dist: current to sp_end
queue.offer(new Step(sp[2], sp[3], getDist(cur.x, cur.y, sp[0], sp[1]) + cur.cost + sp[4]));
}
}
return -1;
}
private int getDist(int x1, int y1, int x2, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
}
```
Last updated
Was this helpful?