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

Leetcode Problem 286. Walls and Gates

286. Walls and Gates

Leetcode Solutions

Breadth-first Search from Gates

  1. Initialize a queue to store the positions of all gates in the grid.
  2. Iterate over the grid to find all gates (cells with value 0) and add their positions to the queue.
  3. Perform a BFS: a. Dequeue a position from the queue. b. Check all four adjacent cells (up, down, left, right). c. If an adjacent cell is an empty room (INF), update its value with the current distance + 1 and enqueue its position. d. If an adjacent cell is a wall or a gate, skip it.
  4. Continue the BFS until the queue is empty.
  5. Once the BFS is complete, all reachable empty rooms will have the shortest distance to a gate.
UML Thumbnail

Brute Force

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...