BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Agents22 of 28 in topic

769. Cheapest path through a grid with weighted cells and limited wall breaks

HardAgents Pro

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.

Functiondef 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.

Topics
Agents
Similar questions
  • Validate tool arguments against a schema before callingHard
  • Schedule an agent's task plan into parallel waves with cycle detectionHard
  • Compact an agent's message history under a token budgetHard
  • Repair a truncated JSON tool call from a streaming modelHard
All Agents problems
Report
769 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import heapq
​
def min_path_cost(grid, breaks=0):
# return the cheapest cost from S to G, or -1
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS