Top 150 InterviewEasy

Walls And Gates

Detailed guide and Python implementation for the 'Walls And Gates' problem.

Problem Statement

Easy

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 (represented by 2147483647): An empty room.

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.

Write a function wallsAndGates(rooms: List[List[int]]) -> List[List[int]] that returns the modified rooms grid.

Constraints
  • m == len(rooms)
  • n == len(rooms[i])
  • 1 <= m, n <= 250
  • rooms[i][j] is -1, 0, or 2147483647

Examples

Example 1
Input
rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
Output
[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Explanation

The empty rooms are filled with the shortest distance to their nearest gate.

Need a Hint?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.