# 2662. Minimum Cost of a Path With Special Roads

````java
```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);
  }
}
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/bfs/2662.-minimum-cost-of-a-path-with-special-roads.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
