KatInterview

Distance Map to the Closest Exit in a Maze Grid

Trees & GraphsAuto-graded · 17 test cases
EasyAuto-gradedTrees & Graphsbfsgridmulti-source-bfs

Last 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) and n == len(grid[0])
  • 1 <= m, n <= 500
  • Each grid[i][j] is 0, 1, or 2.

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.