Skip to content
Decoder

Walls and Gates

Medium

Problem

A floor plan is a grid where -1 is a wall, 0 is a gate, and 2147483647 (call it INF) is an empty room. Fill every empty room with the number of steps to its nearest gate, moving up, down, left or right and never through walls. Rooms that cannot reach any gate keep INF. Change rooms in place; the function returns nothing.

Example 1

INF  -1   0  INF          3  -1   0   1

Example 2

Input
INF INF INF -1
Output
2 2 1 -1

Example 3

INF  -1 INF  -1           1  -1   2  -1

Example 4

  0  -1 INF INF           0  -1   3   4

Constraints

  • 1 <= rooms.length, rooms[i].length <= 250
  • rooms[i][j] is -1, 0 or 2147483647

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.