Walls and Gates

Given a 2D grid map, where -1 represents a wall, 0 represents a gate, and INF represents an empty room, fill each empty room with the distance to its nearest gate.

If it is impossible for an empty room to reach a gate, it should be filled with INF.

Example

I:
INF  -1  0  INF
INF INF INF  -1
INF  -1 INF  -1
  0  -1 INF INF
O:
3  -1   0   1
2   2   1  -1
1  -1   2  -1
0  -1   3   4

From Src to Dst

for the entire graph
    if the room is empty
        BFS(room) to find the nearest gate

Code

The last test case on LC gives this code a TLE. Let N = #nodes. The worst case time complexity is O(N). DFS doesn't help in this case. We are stuck with BFS. How can we do better?

From Dst to Src

We can reverse the starting points. If we start searching from the gates and update the empty rooms we can vastly improve the time complexity. Specifically, O(#gates * N) = O(N).

Notice that we don't need visited since we only put unprocessed empty rooms into the queue.

Code

The question cleverly gives gate the value 0. We can tabulate the distance across the table so we don't really need the for loop that keeps tracks of the levels. We can use the current level rooms[neighbor.row][neighbor.col] = rooms[current.row][current.col] + 1 instead of a level variable.

Last updated