KatInterview

Nearest Exit Distance Map on a Walled Grid

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbfsgridmulti-source-bfs

Last 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, called INF below): 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 2147483647 are 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 m rows and n columns, where m and n can 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, or 2147483647.
  • 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.