Walls and Gates
Find the steps from every cell to its nearest exit
DSA, Medium, Graphs
Which structure or algorithm, and what does it cost.
A floor plan is a list of strings of equal length. # is a wall, E is an exit and . is open floor. You may step to a side neighbour (up, down, left or right) that is not a wall. Write distance_to_exit(plan). It returns a grid of numbers, one for each cell. An exit holds 0. An open cell holds the fewest steps to any exit. A wall holds -1, and so does an open cell that cannot reach an exit.
Examples
Constraints
- 1 <= rows <= 300 and 1 <= columns <= 300.
- Every cell is
#,Eor.. - There may be no exit, and there may be many.
Your answer must contain
- Why the search starts from all exits together; the method; code; time and memory cost; a hand trace of example 1; cells that cannot reach an exit.
Target Aim for O(R * C) time and memory, where R is the number of rows and C the number of columns.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Asking each cell for its nearest exit repeats work. Think about what the cells that are one step from an exit already know.
Hint 2 the approach
Turn the question around and spread outward from the exits. Cells one step away get 1, cells two steps away get 2, and so on.
Hint 3 the key step
Put every exit in the queue together with distance 0. When you reach an open cell with no distance yet, give it the current distance plus 1 and queue it.
Walkthrough
Full walkthrough brute force to best
Brute force
For every open cell, start its own breadth-first search and stop at the first exit it meets. Each search can visit all R * C cells, and there can be about R * C open cells, so this costs O((R * C)^2) time.
Best method
Spread out from the exits instead of searching from each cell. Set every exit to 0 and put all of them in a queue at once. Take a cell off the queue. For each side neighbour that is open floor and has no distance yet, set its distance to this cell's distance plus 1 and queue it. A queue gives distances in rising order, so the first time a cell is reached is by its nearest exit, and that distance is final. Walls are never reached, and open cells that are never reached keep their starting value of -1.
Hand trace
Example 1: the exits (0,2) and (2,0) start in the queue at 0. Round 1 sets (0,3), (0,1), (3,0), (1,0) and (2,1) to 1. Round 2 sets (1,3), (1,1) and (2,2) to 2. Round 3 sets (2,3) and (3,2) to 3. Round 4 sets (3,3) to 4. The walls at (0,0), (1,2) and (3,1) are never reached and stay -1.
Code
from collections import deque
def distance_to_exit(plan):
rows, cols = len(plan), len(plan[0])
dist = [[-1] * cols for _ in range(rows)]
todo = deque()
for r in range(rows):
for c in range(cols):
if plan[r][c] == 'E':
dist[r][c] = 0
todo.append((r, c)) # every exit starts together at distance 0
while todo:
r, c = todo.popleft()
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 plan[nr][nc] == '.' and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
todo.append((nr, nc))
return distTime and memory
O(R * C) time and O(R * C) memory. Each cell gets its distance once and is looked at from four sides. The grid of distances and the queue hold up to R * C cells.
Common mistakes
- Searching from one exit at a time and writing over the cells, if you do not check for a distance already set. A later exit can write a larger number over a smaller one, so start from all exits together.
- Starting a search from every open cell. That repeats work and costs O((R * C)^2).
- Walking through walls or counting steps as straight-line distance. The steps must go around walls.
- Starting open cells at a huge number and returning it for cells no exit reaches. They must be -1.