Nearest Exit Distance Map on a Walled Grid
Trees & GraphsAuto-graded · 22 test casesLast updated
Compute, for every open cell of a grid with walls and exits, the shortest 4-directional distance to any exit using multi-source BFS, leaving unreachable cells unchanged.
Nearest Exit Distance Map on a Walled Grid
You are given a rectangular grid of integers describing a floor plan. Each cell holds one of three kinds of values:
-1: a wall. It cannot be entered.0: an exit.2147483647(that is,2^31 - 1, calledINFbelow): an open, unlabeled cell.
You can move one step at a time between cells that share an edge (up, down, left, right). Moving diagonally is not allowed, and you cannot step onto a wall.
For every open cell, replace its value with the number of steps on the shortest path from that cell to the closest exit. If no exit can be reached from an open cell, leave its value as INF. Walls and exits keep their values.
Update the grid in place and return it.
Details
- Every exit is a valid destination, so the answer for a cell is the minimum over all exits that can be reached.
- Only cells whose value is exactly
2147483647are treated as open cells to be filled. - If the grid has no rows, or its first row is empty, return it unchanged.
Constraints
- The grid has
mrows andncolumns, wheremandncan each be as large as about 1000, so the solution should run in time linear in the number of cells. - Every cell is
-1,0, or2147483647. - The grid may contain zero, one, or many exits.
- Some open cells may be completely enclosed by walls or grid borders and therefore unreachable.
- All rows have the same length.
Examples
Example 1
Input: fill_exit_distances([[2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1], [2147483647, -1, 2147483647, -1], [0, -1, 2147483647, 2147483647]])
Output: [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]]
Example 2
Input: fill_exit_distances([[0, 2147483647, 2147483647], [-1, -1, 2147483647], [2147483647, 2147483647, 2147483647]])
Output: [[0, 1, 2], [-1, -1, 3], [6, 5, 4]]
Example 3
Input: fill_exit_distances([[2147483647, -1, 2147483647], [2147483647, -1, 2147483647], [2147483647, -1, 0]])
Output: [[2147483647, -1, 2], [2147483647, -1, 1], [2147483647, -1, 0]]
Hints
Hint 1
Computing a separate search from every open cell, or from every exit one after another, repeats a lot of work. Think about how to explore from all exits at the same time.
Hint 2
Put every exit into one queue before starting. A breadth-first search processes cells in order of increasing distance, so the first time you reach an open cell is via a shortest path.
Hint 3
You can use the grid itself as the visited marker: only step into neighbors that still equal INF, write the new distance immediately when enqueuing, and walls, exits, and already-filled cells are then skipped automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the grid as an unweighted graph where each non-wall cell is a node connected to its four neighbors. The goal is the distance from each open cell to its nearest exit, which is a "nearest of many sources" problem. The standard tool is a multi-source breadth-first search.
- Scan the grid once and add every exit (value
0) to a queue. All of them are at distance 0. - Repeatedly remove a cell from the front of the queue. For each of its four neighbors that is inside the grid and still equals
INF, writecurrent + 1into that neighbor and add it to the queue. - When the queue is empty, return the grid.
Why it is correct
Imagine an extra virtual node connected to every exit with a zero-length edge. The distance from a cell to its nearest exit equals its distance from that virtual node, and seeding the queue with all exits is exactly the first step of a BFS from it.
BFS removes cells in non-decreasing order of distance, so the first time an open cell is discovered, it is discovered from a cell at the smallest possible distance. That makes the value written at discovery time the shortest distance, and it never needs to change.
Checking == INF is enough: walls (-1) and exits (0) never match, and cells that have already been filled hold a finite value, so they are never revisited. The grid doubles as the visited set. Open cells that cannot be reached from any exit are never adjacent to a processed cell, so they keep the value INF.
Complexity
- Time: O(m * n). Each cell is enqueued at most once and examines four neighbors, independent of how many exits exist.
- Space: O(m * n) in the worst case for the queue (for example, a grid made entirely of exits). Apart from the queue, the grid is updated in place.
Reference solution
from collections import deque
from typing import List
def fill_exit_distances(grid: List[List[int]]) -> List[List[int]]:
if not grid or not grid[0]:
return grid
INF = 2147483647
rows, cols = len(grid), len(grid[0])
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 0:
queue.append((r, c))
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == INF:
grid[nr][nc] = grid[r][c] + 1
queue.append((nr, nc))
return grid