Start learning free

LESSON 529 OF 634 · GRAPHS

Walls and Gates in C++

Practice O(m · n)

You get a grid, rooms, with m rows and n columns. It is a vector of rows, and each row is a vector of integers. Each cell holds one of three values:

  • -1 is a wall.
  • 0 is a gate.
  • 2147483647 is an empty room.

For each empty room, find the closest gate. Write the number of steps to it into the room's cell. Change rooms in place and return nothing.

A step moves one cell up, down, left or right. Steps can't go through walls. A room that no gate can reach keeps the value 2147483647.

 

Example 1:

Input: rooms = [
  [2147483647, 2147483647, -1, 0],
  [0, 2147483647, 2147483647, 2147483647],
  [2147483647, -1, -1, 2147483647]
]
Output: [
  [1, 2, -1, 0],
  [0, 1, 2, 1],
  [1, -1, -1, 2]
]
Explanation: There are two gates.
Each room gets the steps to the closer one.
The room at row 1, column 2 (counting from 0) is 2 steps from each gate.

Example 2:

Input: rooms = [
  [0, -1, 2147483647],
  [2147483647, -1, 2147483647],
  [2147483647, 2147483647, 2147483647]
]
Output: [
  [0, -1, 6],
  [1, -1, 5],
  [2, 3, 4]
]
Explanation: The walls block the short way to the top-right room.
The path from the gate goes down, right, then up.
That takes 6 steps.

Example 3:

Input: rooms = [
  [2147483647, -1, 0],
  [-1, 2147483647, 2147483647]
]
Output: [
  [2147483647, -1, 0],
  [-1, 2, 1]
]
Explanation: Walls close in the top-left room.
Diagonal moves don't count.
No gate can reach the room, so it keeps 2147483647.

 

Constraints:

  • 1 to 250 rows.
  • 1 to 250 columns.
  • All rows have the same length.
  • Each cell is -1, 0 or 2147483647.

Note:

Your solution should run in O(m · n) time.

STEP 1 OF 14
    Ctrl + Enter to check

    Walls And Gates in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free