Walls and Gates

Medium Graphs

rooms is a grid of m rows and n columns. Each cell holds -1 for a wall, 0 for a gate or 2147483647 for an empty room.

A step goes from a cell to the one above, below, left or right of it, and never into a wall. The distance from a room to a gate is the fewest steps a walk from one to the other takes.

Change rooms in place: replace every empty room with its distance to the nearest gate. A room that no gate can reach keeps 2147483647, and walls and gates stay as they are. Return nothing.

Example 1

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

Example 2

Input: rooms = [[0,2147483647,-1,2147483647],[2147483647,2147483647,-1,2147483647],[2147483647,2147483647,-1,2147483647]]
Output: [[0,1,-1,2147483647],[1,2,-1,2147483647],[2,3,-1,2147483647]]

The column right of the wall cannot be reached from the gate, so it keeps 2147483647.

Example 3

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

Constraints

  • 1 ≤ m, n ≤ 300
  • rooms[i][j] is -1, 0 or 2147483647

More Graphs

All Graphs problems