286. Walls and Gates
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to fill each empty room, represented by INF (2147483647), with the distance to its nearest gate, represented by 0. Walls, represented by -1, are impassable. This is a classic shortest path problem on a grid. We need to find, for each empty room, the minimum number of steps to reach any gate.
Solution
Walls and Gates in Python
from collections import deque
class Solution:
def wallsAndGates(self, rooms: list[list[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
if not rooms or not rooms[0]:
return
m, n = len(rooms), len(rooms[0])
q = deque()
INF = 2147483647
# 1. Initialize the queue with all gates
for r in range(m):
for c in range(n):
if rooms[r][c] == 0:
q.append((r, c))
# Directions for neighbors (up, down, left, right)
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# 2. Perform multi-source BFS
while q:
r, c = q.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
# Check boundaries and if the room is an empty room (INF)
if 0 <= nr < m and 0 <= nc < n and rooms[nr][nc] == INF:
# Update distance and enqueue the new room
rooms[nr][nc] = rooms[r][c] + 1
q.append((nr, nc))
Walls and Gates in Java
class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.length == 0 || rooms[0].length == 0) {
return;
}
int m = rooms.length;
int n = rooms[0].length;
Queue<int[]> queue = new LinkedList<>();
final int INF = 2147483647;
// 1. Initialize the queue with all gates
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (rooms[i][j] == 0) {
queue.offer(new int[]{i, j});
}
}
}
// Directions for neighbors (up, down, left, right)
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// 2. Perform multi-source BFS
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int r = curr[0];
int c = curr[1];
for (int[] dir : dirs) {
int nr = r + dir[0];
int nc = c + dir[1];
// Check boundaries and if the room is an empty room (INF)
if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] == INF) {
// Update distance and enqueue the new room
rooms[nr][nc] = rooms[r][c] + 1;
queue.offer(new int[]{nr, nc});
}
}
}
}
}
Walls and Gates in C++
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
if (rooms.empty() || rooms[0].empty()) {
return;
}
int m = rooms.size();
int n = rooms[0].size();
queue<pair<int, int>> q;
const int INF = 2147483647;
// 1. Initialize the queue with all gates
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (rooms[i][j] == 0) {
q.push({i, j});
}
}
}
// Directions for neighbors (up, down, left, right)
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// 2. Perform multi-source BFS
while (!q.empty()) {
pair<int, int> curr = q.front();
q.pop();
int r = curr.first;
int c = curr.second;
for (auto& dir : dirs) {
int nr = r + dir[0];
int nc = c + dir[1];
// Check boundaries and if the room is an empty room (INF)
if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] == INF) {
// Update distance and enqueue the new room
rooms[nr][nc] = rooms[r][c] + 1;
q.push({nr, nc});
}
}
}
}
};
Walls and Gates in TypeScript
/**
Do not return anything, modify rooms in-place instead.
*/
function wallsAndGates(rooms: number[][]): void {
if (!rooms || rooms.length === 0 || rooms[0].length === 0) {
return;
}
const m = rooms.length;
const n = rooms[0].length;
const queue: [number, number][] = [];
const INF = 2147483647;
// 1. Initialize the queue with all gates
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (rooms[i][j] === 0) {
queue.push([i, j]);
}
}
}
// Directions for neighbors (up, down, left, right)
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
// 2. Perform multi-source BFS
while (queue.length > 0) {
const [r, c] = queue.shift()!;
for (const [dr, dc] of dirs) {
const nr = r + dr;
const nc = c + dc;
// Check boundaries and if the room is an empty room (INF)
if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] === INF) {
// Update distance and enqueue the new room
rooms[nr][nc] = rooms[r][c] + 1;
queue.push([nr, nc]);
}
}
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.