Distance Map to the Closest Exit in a Maze Grid
Trees & GraphsAuto-graded · 17 test casesLast updated
Compute, for every cell of a grid with walls and exits, the fewest steps to the nearest exit, marking walls and cut-off cells as -1, using multi-source BFS.
Distance Map to the Closest Exit
You are given a rectangular maze as a 2D list of integers with m rows and n columns. Each cell holds one of three values:
0: a free cell that can be walked through.1: a wall that can never be entered.2: an exit.
From any cell you may step to one of its four orthogonal neighbors (up, down, left, right), as long as the neighbor lies inside the grid and is not a wall. Every step costs exactly 1.
Build and return a new grid of the same size where each entry is computed as follows:
- For an exit cell, the value is
0. - For a free cell, the value is the minimum number of steps needed to reach any exit. If no exit can be reached, the value is
-1. - For a wall cell, the value is
-1.
The input grid must not be modified. If the grid contains no exits, every entry of the result is -1.
Constraints
m == len(grid)andn == len(grid[0])1 <= m, n <= 500- Each
grid[i][j]is0,1, or2.
Examples
Example 1
Input: closest_exit_distances([[0, 0, 0], [0, 1, 0], [0, 0, 2]])
Output: [[4, 3, 2], [3, -1, 1], [2, 1, 0]]
Example 2
Input: closest_exit_distances([[2, 0], [1, 1]])
Output: [[0, 1], [-1, -1]]
Hints
Hint 1
Running a separate search from each free cell is far too slow for a 500 x 500 grid. Think about whether the search can be run in the opposite direction.
Hint 2
Because every step costs 1 and moves are symmetric, the distance from a cell to an exit equals the distance from that exit to the cell. Start one search from all exits at the same time.
Hint 3
Initialize the answer grid with -1 and use it as the visited marker. Put every exit in the queue with distance 0, and mark a cell when you enqueue it, so walls and unreachable cells simply keep -1.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Searching from every free cell toward the exits would cost up to O((m·n)²) in total, which is too slow for a 500 x 500 grid.
Instead, reverse the search. Moves are symmetric and each costs 1, so the distance from a cell to an exit equals the distance from that exit to the cell. This lets us run a single multi-source breadth-first search that begins at all exits simultaneously.
- Create a result grid filled with
-1. This value doubles as "not visited yet" and as the final answer for walls and unreachable cells. - Set every exit to
0and push it into a FIFO queue. - Repeatedly pop a cell. For each of its four neighbors that is inside the grid, is not a wall, and still has value
-1, set it to the current distance plus one and push it. - When the queue empties, return the result grid.
Why it works
BFS visits cells in non-decreasing order of distance. Since all exits start at distance 0, the queue always holds cells from at most two consecutive distance levels. When a cell is reached for the first time, it is reached from a cell at the smallest possible distance, so no shorter route from any exit exists. That first assignment is therefore the minimum over all exits and is never changed afterward. Marking a cell on enqueue guarantees each cell enters the queue at most once. Walls are never entered, and free cells that no exit can reach are never assigned, so both keep -1, as required. With no exits the queue starts empty and everything stays -1.
Complexity
- Time: O(m·n). Each cell is enqueued and dequeued at most once, with four neighbor checks each.
- Space: O(m·n) for the output grid and the queue.
Reference solution
from collections import deque
from typing import List
def closest_exit_distances(grid: List[List[int]]) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
dist = [[-1] * n for _ in range(m)]
queue = deque()
# Seed the search with every exit at distance 0.
for r in range(m):
for c in range(n):
if grid[r][c] == 2:
dist[r][c] = 0
queue.append((r, c))
# Expand outward one layer at a time.
while queue:
r, c = queue.popleft()
nxt = dist[r][c] + 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] != 1 and dist[nr][nc] == -1:
dist[nr][nc] = nxt
queue.append((nr, nc))
return dist