Magicsheet logo

Minimum Cost of a Path With Special Roads

Medium
87.6%
Updated 6/1/2025

Minimum Cost of a Path With Special Roads

What is this problem about?

In the Minimum Cost of a Path With Special Roads problem, you start at start and want to reach target on a 2D plane. You can always move between any two points (x1, y1) and (x2, y2) with a cost of |x1 - x2| + |y1 - y2| (Manhattan distance). However, there are also "special roads" that connect two specific points with a fixed (often cheaper) cost. You need to find the minimum cost to reach the target.

Why is this asked in interviews?

This is a classic Shortest Path interview question for companies like Samsung. It tests your ability to model a problem as a graph and apply Dijkstra's Algorithm. The challenge is that the plane has infinite points, so you must realize that only the start, target, and the endpoints of the "special roads" are relevant nodes in your graph.

Algorithmic pattern used

The Dijkstra's Algorithm with Heap interview pattern is the way to solve this.

  1. Collect all "interesting" points: start, target, and all (x1, y1), (x2, y2) from the special roads.
  2. Use a Priority Queue (Heap) to store (cost, x, y).
  3. From the current point, you can:
    • Move directly to the target.
    • Take any of the "special roads" (cost = cost to reach road start + road cost).
  4. Since the number of special roads is small (e.g., 200), the number of nodes is manageable for Dijkstra.

Example explanation

Start: (1, 1), Target: (10, 10). Special road: (1, 1) to (1, 10) cost 2.

  1. Direct distance to target: |10-1| + |10-1| = 18.
  2. Via special road:
    • Cost to (1, 1): 0.
    • Use road to (1, 10): cost 2.
    • Distance from (1, 10) to target (10, 10): |10-1| + |10-10| = 9.
    • Total: 0 + 2 + 9 = 11.
  3. The minimum cost is 11.

Common mistakes candidates make

  • Not including all road points: Forgetting that you can go from the end of one special road to the start of another using Manhattan distance.
  • Modeling infinite points: Trying to use a grid-based BFS or DP, which is impossible due to the coordinate range.
  • Inefficient Dijkstra: Not using a Priority Queue or not updating the "minimum cost to reach point P" correctly.

Interview preparation tip

When faced with "Special Roads" or "Portals" on a 2D plane, think of Dijkstra on a Sparse Graph. The "nodes" of your graph are just the special locations. Every node is connected to every other node by the standard Manhattan distance, plus the special connections.

Similar Questions