bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 542. 01 Matrix

542. 01 Matrix

Leetcode Solutions

Breadth-First Search (BFS) Approach

  1. Initialize an empty queue and a matrix dist with the same dimensions as mat to store the distances.
  2. Iterate over the matrix and for each cell that contains 0, add its coordinates to the queue and set its distance in dist to 0.
  3. For each cell that contains 1, set its distance in dist to a large value (indicating that the distance is not yet calculated).
  4. Perform a BFS: while the queue is not empty, remove the front cell from the queue. For each of its 4 adjacent cells (up, down, left, right), if the adjacent cell is within bounds and its distance in dist is greater than the current cell's distance plus 1, update the adjacent cell's distance and add it to the queue.
  5. Once the BFS is complete, return the dist matrix.
UML Thumbnail

Dynamic Programming Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR