KatInterview

Cheapest Dungeon Escape Through Monster Cells

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphsgriddijkstrashortest-path

Last 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:

  • S marks the starting cell.
  • E marks the exit cell.
  • . marks an open floor cell.
  • M marks 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 M costs 1.
  • Entering any other non-wall cell (., S, or E) costs 0.
  • 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 S and at most one E.
  • The grid may be empty (return -1).
  • The answer is a non-negative integer, or -1 when 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.