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.
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.
The Dijkstra's Algorithm with Heap interview pattern is the way to solve this.
start, target, and all (x1, y1), (x2, y2) from the special roads.(cost, x, y).target.Start: (1, 1), Target: (10, 10).
Special road: (1, 1) to (1, 10) cost 2.
|10-1| + |10-1| = 18.(1, 1): 0.(1, 10): cost 2.(1, 10) to target (10, 10): |10-1| + |10-10| = 9.0 + 2 + 9 = 11.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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Path with Maximum Probability | Medium | Solve | |
| Minimum Cost to Buy Apples | Medium | Solve | |
| Find Minimum Time to Reach Last Room I | Medium | Solve | |
| Find Minimum Time to Reach Last Room II | Medium | Solve | |
| Minimum Cost Path with Edge Reversals | Medium | Solve |