Walls And Gates Problem

Walls and Gates Problem – Medium Level Problem

You are given a 2D grid with m × n cells, where each cell can have one of these three values:

  • -1 – Water (cannot be crossed).
  • 0 – A treasure chest.
  • INF – Land that can be crossed (represented by 2147483647).
Walls and Gates Problem for DSA

Constraints :

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • grid[i][j] is one of {-1, 0, 2147483647}

Walls and Gates Problem - Solution

Recommendation for Time and Space Complexity – Aim for O(m × n) time and space, where m is rows and n is columns.

Hints for solving problems

Hint 1

A brute force approach checks each land cell and runs BFS to find the nearest treasure, which takes O((m × n)²). Instead, think about solving it in reverse.

Hint 2

Instead of starting from each land cell, start BFS from all treasure chests at once. This Multi-Source BFS updates distances level by level, ensuring no cell is revisited.

Hint 3

Add all treasure chest positions to a queue and process them level by level. For each cell, mark it visited, update its distance, and add its unvisited land neighbors to the queue.

There are mainly 3 approach to solve this problem-

  1. Brute Force(Backtracking) Method
  2. Breadth First Search Method

1. Brute Force(Backtracking) Method

In this approach, recursively explore all possible paths from each gate to every empty room. Update the shortest distance for each room along the way. Though simple, it is inefficient for large grids due to the high time complexity caused by repeated visits to the same rooms.

  • Time complexity: O(m * n * 4^(m*n))
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns in the grid.

Code

2. Breadth First Search Method

Start BFS from each gate (value 0) one at a time. Update distances for reachable empty rooms and stop exploring when you encounter walls or visited cells. While better than brute force, this still processes each gate separately, leading to redundant work.

  • Time complexity: O((m * n)^2)
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns in the grid.

Code

More Articles