You get a grid, rooms, with m rows and n columns. It is an array of rows, and each row is an array of integers. Each cell holds one of three values:
-1is a wall.0is a gate.2147483647is 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,0or2147483647.
Note:
Your solution should run in O(m · n) time.
Free plan: 30 tutor messages. Premium is unlimited.
