Walls and Gates — LeetCode 286 Python Solution

MediumLeetCode PremiumBreadth-First SearchArrayMatrix
Problem
#286
Reading time
3 min

The problem

You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle.

Example

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]]

Python solution

Python
class Solution:
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        """
        Do not return anything, modify rooms in-place instead.
        """
        m, n = len(rooms), len(rooms[0])
        inf = 2**31 - 1
        q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0])
        d = 0
        while q:
            d += 1
            for _ in range(len(q)):
                i, j = q.popleft()
                for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    x, y = i + a, j + b
                    if 0 <= x < m and 0 <= y < n and rooms[x][y] == inf:
                        rooms[x][y] = d
                        q.append((x, y))

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 286. Walls and Gates is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 286. Walls and Gates?
LeetCode 286. Walls and Gates is rated Medium on LeetCode.
What is the time complexity of LeetCode 286. Walls and Gates?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 286. Walls and Gates?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 286. Walls and Gates cover?
LeetCode 286. Walls and Gates is tagged Breadth-First Search, Array and Matrix on LeetCode.
Is LeetCode 286. Walls and Gates a premium problem?
Yes. LeetCode 286. Walls and Gates is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview