Cheapest Dungeon Escape Through Monster Cells
Trees & GraphsAuto-graded · 15 test casesLast updated
Find the minimum number of monster cells entered on any route from start to exit in a grid with walls, using a weighted shortest-path search such as Dijkstra or 0-1 BFS.
You are given a dungeon map as a list of equal-length strings. Each character describes one cell:
Smarks the starting cell.Emarks the exit cell..marks an open floor cell.Mmarks a cell occupied by a monster.#marks a wall.
You may move one step at a time to an adjacent cell in one of four directions: up, down, left, or right. You may never step into a wall or leave the grid.
Cost rules
- Entering a cell containing
Mcosts1. - Entering any other non-wall cell (
.,S, orE) costs0. - The total cost of a route is the sum of the costs of every cell you enter. The starting cell is never charged, because you do not enter it.
- The length of the route does not matter, only its total cost.
Return the minimum total cost of any route from S to E. If no route exists, return -1.
If the grid is empty, or if it has no S or no E, return -1.
Constraints
- The grid is a list of strings, each of the same length.
- Each character is one of
S,E,.,M,#. - There is at most one
Sand at most oneE. - The grid may be empty (return
-1). - The answer is a non-negative integer, or
-1when the exit cannot be reached.
Examples
Example 1
Input: min_monsters_to_exit(['S.M', '..E'])
Output: 0
Example 2
Input: min_monsters_to_exit(['S#M', '##E'])
Output: -1
Example 3
Input: min_monsters_to_exit(['S.M', 'M.E'])
Output: 0
Hints
Hint 1
A plain breadth-first search minimizes the number of steps, not the number of monsters. A longer route through empty floor can be cheaper.
Hint 2
Every move has a non-negative cost (0 or 1), so a shortest-path algorithm for weighted graphs applies. Think Dijkstra with a min-heap, or a deque-based variant.
Hint 3
Charge the cost of the cell you move into, not the cell you leave. Skip outdated heap entries, and return -1 if the search finishes without reaching the exit.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat every non-wall cell as a node in a graph. Moving to a neighbouring cell is an edge whose weight is the cost of the cell being entered: 1 for M, 0 otherwise.
Breadth-first search would minimize the number of steps, which is the wrong objective here. Since all weights are non-negative, Dijkstra's algorithm is the right tool:
- Locate
SandE. If either is missing (or the grid is empty), return-1. - Keep a table of best-known costs, initialized to infinity, with
Sset to0. - Push
(0, row, col)forSinto a min-heap. - Pop the cheapest entry. If its cost is larger than the recorded best for that cell, it is stale, so skip it.
- If the popped cell is
E, return its cost. - Otherwise, for each in-bounds, non-wall neighbour, compute the cost of entering it. If that improves the neighbour's recorded best, update it and push it.
- If the heap empties without reaching
E, return-1.
Because the weights are only 0 and 1, a 0-1 BFS with a deque (0-cost moves to the front, 1-cost moves to the back) gives the same answer in linear time.
Why it is correct
When a cell is popped with a cost equal to its recorded best, no cheaper route to it can exist. Any alternative route would pass through a cell still in the heap with at least that cost, and adding non-negative weights never reduces a total. So the first time E is popped, its cost is optimal. If E is never popped, it is not reachable. The start cell is never charged because costs are added only when entering a neighbour.
Complexity
With V = rows × cols cells:
- Time: O(V log V), since there are at most 4V heap pushes.
- Space: O(V) for the distance table and heap.
Reference solution
import heapq
from typing import List
def min_monsters_to_exit(grid: List[str]) -> int:
if not grid or not grid[0]:
return -1
rows, cols = len(grid), len(grid[0])
start = end = None
for r in range(rows):
for c in range(cols):
if grid[r][c] == 'S':
start = (r, c)
elif grid[r][c] == 'E':
end = (r, c)
if start is None or end is None:
return -1
dist = [[float('inf')] * cols for _ in range(rows)]
dist[start[0]][start[1]] = 0
heap = [(0, start[0], start[1])]
enter_cost = {'.': 0, 'M': 1, 'S': 0, 'E': 0}
while heap:
cost, r, c = heapq.heappop(heap)
if cost != dist[r][c]:
continue
if (r, c) == end:
return cost
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != '#':
new_cost = cost + enter_cost[grid[nr][nc]]
if new_cost < dist[nr][nc]:
dist[nr][nc] = new_cost
heapq.heappush(heap, (new_cost, nr, nc))
return -1