769. Cheapest path through a grid with weighted cells and limited wall breaks
A robot or game agent plans a route on a grid. Start with plain walls, then make some cells more expensive to enter, then allow the agent to break through a few walls. Each stage changes the search, not just the code around it.
Write min_path_cost(grid, breaks=0). grid is a list of equal-length strings. 'S' is the start and 'G' the goal (exactly one each), '#' is a wall, '.' costs 1 to enter, and a digit '1' to '9' costs that much to enter. Entering 'G' costs 1. You move up, down, left or right. You may enter at most breaks wall cells; entering a wall costs 1 and uses one break. Return the minimum total cost to reach G, or -1 if it cannot be reached.
def min_path_cost(grid, breaks=0)Example 1
Input: min_path_cost(['S.#', '..#', '#.G'])
Output: 4
Example 2
Input: min_path_cost(['S#G'])
Output: -1, and min_path_cost(['S#G'], breaks=1) returns 2
Example 3
Input: (min_path_cost(['S#G']), min_path_cost(['S#G'], breaks=1))
Output: (-1, 2)
Constraints
- Grid up to 300 x 300.
- breaks up to 5.
- Exactly one S and one G.
Hint 1
Find S first.
Hint 2
Push (cost, row, col, used) on a heap.
Hint 3
Skip a popped entry if a cheaper one for the same state was already found.
Common mistakes
- Keeping BFS after weights are added.
- Tracking visited per cell only, which wrongly blocks a path that arrives with more breaks left.
- Forgetting that entering G also costs 1.
Understand the idea
Path finding questions grow in stages: unweighted grid (BFS), weighted cells (Dijkstra), and extra resources such as keys, fuel or wall breaks (add the resource to the state). The search algorithm barely changes between stages; what changes is the definition of a state and the cost of an edge. Saying that out loud early is what interviewers look for in staged rounds.