InterviewPrepKit

Home / Coding / Graphs

Walls and Gates 🔒

medium Original ↗
Solving tips
  • 'Distance to the nearest gate' from all rooms at once is multi-source BFS: seed the queue with every gate at distance 0, then expand rings; O(m*n) beats the O((m*n)^2) BFS-per-room trap.
  • Because all gates start together and BFS grows in distance order, the first gate wave to reach a room writes its minimum distance and the closest gate wins.
  • Use the INF sentinel itself as 'unvisited': only write a room when it still equals INF, which also enforces first-write-wins with no separate visited set.
  • Pitfall: walls (-1) are not INF so the guard already skips them, and don't run single-source BFS per gate and combine (that is the slow trap).

Problem

You’re given an m x n grid where each cell is one of:

  • -1 — a wall (impassable),
  • 0 — a gate,
  • 2147483647 (i.e. 2³¹ - 1, call it INF) — an empty room.

Fill each empty room with the distance to its nearest gate, moving only up/down/left/right and never through walls. If a room cannot reach any gate, leave it as INF. Modify the grid in place.

Examples

  • INF  -1   0  INF          3  -1   0   1
    INF INF INF  -1     →      2   2   1  -1
    INF  -1 INF  -1            1  -1   2  -1
      0  -1 INF INF            0  -1   3   4

    Each room now holds its shortest step-count to the closest gate; the wall cells (-1) and gate cells (0) are unchanged.

  • 0 INF          0 1

    The single room is one step from the gate → 1.

  • INF -1          INF -1

    No gate exists, so the room stays INF (unreachable).

Constraints

  • Up to m, n a few hundred each — an O(m·n) solution is expected.
  • Gates may be plentiful; distances are the minimum over all gates, not a single fixed source.

Think about it first

Hint 1 "Distance to the nearest gate" over an unweighted grid is a shortest-path question. Running a separate BFS outward from every empty room to find its closest gate works but repeats an enormous amount of exploration.
Hint 2 Reverse the direction: expand outward from the gates instead of from the rooms. If you start every gate at distance 0 simultaneously, the wavefront reaches each room in exactly its nearest-gate distance.
Hint 3 Seed a single BFS queue with all gates at once — this is multi-source BFS. The first time the wave touches a room, that's its shortest distance; because all sources start together, gates naturally "compete" and the closest one wins.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.