Walls and Gates

BFS

Problem

You are given an m x n grid rooms initialized with these three possible values.

  • -1 A wall or an obstacle.

  • 0 A gate.

  • INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

Thought Process

  • We are going to pay attention to the '0' cells and apply BFS to find neighboring INF values

  • BFS covers all neighbors and then moves forward

  • Adding all the gates ('0') into the queue gurantees that all the updated values is the minimal value to the nearest target. A good way to think about it is below:

  • BFS:

      1. Store all 0's in a queue

      2. Pull the 0's from the queue and check if the neighbors are INF then update

Solution

Time Complexity

  • Time: O(m*n)

  • Space: O(m*n)

Last updated

Was this helpful?