KatInterview

Fill Rooms With Distance to Nearest Exit

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgraphsgrid

Last updated

Tests multi-source BFS on a grid to propagate shortest walking distances from all exits simultaneously to every reachable empty room.

Fill Rooms With Distance to Nearest Exit

You are given a rectangular floor plan as a 2D grid of integers. Each cell holds one of three values:

  • -1 — a wall (impassable)
  • 0 — an exit
  • 2147483647 — an empty room (written as INF below for readability)

Produce a new grid with the same dimensions. Copy walls and exits unchanged. For every empty room, replace INF with the shortest walking distance to the nearest exit, measured in steps along the four cardinal directions (up, down, left, right). Walls block movement. A room that cannot reach any exit must keep the value INF.

Movement is strictly 4-directional; diagonal moves are not allowed. Each step between adjacent non-wall cells counts as distance 1.

Constraints

  • 0 <= rows, cols <= 250
  • The grid contains only the values -1, 0, or 2147483647
  • There may be zero exits, zero empty rooms, or both
  • An empty room with no path to any exit retains 2147483647 in the output
  • Do not modify the input grid; return a new grid

Examples

Example 1

Input: fill_rooms_with_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]]

Hints

Hint 1

Instead of searching from each room outward, think about what happens if you start the search from every exit at the same time.

Hint 2

A standard BFS explores cells in non-decreasing order of distance. The first time a cell is reached, that distance is already the shortest — no need to revisit it.

Hint 3

You can tell whether a cell has already been assigned a distance by checking whether its value is still INF. Use this to avoid a separate visited structure.