Minimum Cost of a Path With Special Roads - Problem

You are given an array start where start = [startX, startY] represents your initial position (startX, startY) in a 2D space. You are also given the array target where target = [targetX, targetY] represents your target position (targetX, targetY).

The cost of going from a position (x1, y1) to any other position in the space (x2, y2) is |x2 - x1| + |y2 - y1| (Manhattan distance).

There are also some special roads. You are given a 2D array specialRoads where specialRoads[i] = [x1i, y1i, x2i, y2i, costi] indicates that the ith special road goes in one direction from (x1i, y1i) to (x2i, y2i) with a cost equal to costi. You can use each special road any number of times.

Return the minimum cost required to go from (startX, startY) to (targetX, targetY).

Input & Output

Example 1 — Basic Case with Special Road
$ Input: start = [1,1], target = [4,1], specialRoads = [[1,2,3,3,2],[3,4,4,1,1]]
Output: 5
💡 Note: The optimal path: (1,1) → (1,2) [cost=1] → (3,3) [special road cost=2] → (4,1) [cost=3]. Total: 1+2+3=6. Direct path: |4-1|+|1-1|=3. Another path via second special road gives cost 5, which is optimal.
Example 2 — Direct Path is Better
$ Input: start = [3,2], target = [5,7], specialRoads = [[3,2,3,4,4],[3,3,5,7,6]]
Output: 7
💡 Note: Direct Manhattan distance: |5-3|+|7-2| = 2+5 = 7. Using special roads would be more expensive, so direct path is optimal.
Example 3 — Multiple Special Roads
$ Input: start = [1,1], target = [2,3], specialRoads = [[1,1,2,2,1],[2,2,2,3,1]]
Output: 2
💡 Note: Use both special roads: (1,1) → (2,2) [special cost=1] → (2,3) [special cost=1]. Total: 1+1=2. Direct path would be |2-1|+|3-1|=3.

Constraints

  • start.length == 2
  • target.length == 2
  • 1 ≤ specialRoads.length ≤ 200
  • specialRoads[i].length == 5
  • start[i], target[i], specialRoads[i][j] are integers
  • 1 ≤ start[i], target[i], specialRoads[i][j] ≤ 10⁵

Visualization

Tap to expand
Minimum Cost Path: Manhattan Distance + Special RoadsStart (1,1)Target (4,1)(1,2)(3,3)(3,4)(4,1)Direct: |4-1|+|1-1| = 3cost=1special: cost=2to (3,4): cost=5special: cost=1Minimum Cost: 5 (via special road from (3,4) to (4,1))
Understanding the Visualization
1
Input
Start point, target point, and available special roads with their costs
2
Process
Compare direct Manhattan distance vs routes using special roads
3
Output
Return minimum cost among all possible paths
Key Takeaway
🎯 Key Insight: Model as shortest path problem - consider all possible routes through special road endpoints
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
8.5K Views
Medium Frequency
~35 min Avg. Time
180 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen