Steps to the Nearest Fire Exit

Medium · Graphs, BFS & DFS · about 20 min

A floor plan is a grid: 0 is a wall, 1 is open floor and 2 is a fire exit. People walk up, down, left or right, never through walls. Walking through an exit cell is allowed.

Return a grid of the same size where:

  • each exit cell is 0,
  • each open floor cell holds the fewest steps needed to reach any exit,
  • walls and open cells that cannot reach any exit are -1.

Do not change the input grid.

Example:

exit_distances([[2, 1, 1], [0, 0, 1], [1, 1, 1]]) → [[0, 1, 2], [-1, -1, 3], [6, 5, 4]]

Hints

  • Searching from each room separately repeats a lot of work. Turn it around and search from the exits.
  • Start one breadth-first search with every exit in the queue at distance 0.
  • Fill the answer with -1 first. A cell gets a distance the first time the search reaches it, and is never changed after that.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems