01 Matrix

BFS

Problem

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Thought Process

  • BFS

  • Store 0's in the queue so we can look at their neighbors

Solution

  • Notice here we don't care about the "deepest level" or using levels in anyways (like in Rotting Oranges or As Far Land As Possible). This is why we don't utilize the levels in this BFS problem

Time Complexity

  • Time: O(n*n)

  • Space: O(n*n) since we are storing all the 0's and 1's in the queue

Last updated

Was this helpful?