oneby7

Graphs Fewest steps with BFS

444. Walls and Gates

Medium

You are given a floor plan as a grid of integers, rooms, with m rows and n columns. Each cell holds one of three values:

  • -1: a wall.
  • 0: a gate.
  • 2147483647: an empty room. This value is 231 − 1, and we call it INF.

Fill each empty room with the number of steps from it to its nearest gate. A step moves to the cell directly above, below, left or right, and a walk never enters a wall. If no gate can be reached from a room, leave it as INF.

Change rooms in place and return nothing. Walls and gates keep their values.

Example 1

Input: rooms = [[0, 2147483647, -1, 2147483647, 2147483647], [2147483647, -1, 2147483647, 2147483647, 0], [2147483647, 2147483647, 2147483647, -1, 2147483647], [-1, 2147483647, -1, 2147483647, 2147483647]]

Output: [[0,1,-1,2,1], [1,-1,2,1,0], [2,3,3,-1,1], [-1,4,-1,3,2]]

Explanation: The room at row 3, column 1 is four steps from the top-left gate, the most of any room. The room at row 2, column 2 is four steps from the top-left gate but only three from the gate on the right, so it gets 3.

Example 2

Input: rooms = [[2147483647, -1, 0], [-1, 2147483647, 2147483647], [2147483647, -1, 2147483647]]

Output: [[2147483647,-1,0],[-1,2,1],[2147483647,-1,2]]

Explanation: Walls shut in the top-left and bottom-left rooms, so no gate can reach them and they stay INF.

Example 3

Input: rooms = [[2147483647, 2147483647, 0, 2147483647], [-1, -1, 2147483647, -1], [2147483647, 2147483647, 2147483647, 2147483647]]

Output: [[2,1,0,1],[-1,-1,1,-1],[4,3,2,3]]

Explanation: The middle row has one gap, right under the gate. The room in the bottom-left corner walks down through that gap and then left, four steps in all.

Check your understanding

Work out the answer for this input before you write any code.

rooms = [[0, 2147483647, 2147483647, -1, 2147483647], [2147483647, -1, 2147483647, -1, 2147483647], [2147483647, -1, 2147483647, 2147483647, 0]]

Constraints

  • m == rooms.length, n == rooms[i].length
  • 1 ≤ m, n ≤ 300
  • rooms[i][j] is -1, 0 or 231 − 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.