Back to articles
LeetCode 286: Walls And Gates — Step-by-Step Visual Trace

LeetCode 286: Walls And Gates — Step-by-Step Visual Trace

via Dev.totracelit

Medium — BFS | Matrix | Graph The Problem Fill each empty room with the distance to its nearest gate, where rooms are represented by a 2D grid with gates (0), walls (-1), and empty rooms (INF). Approach Use multi-source BFS starting from all gates simultaneously. For each gate, perform BFS to explore neighboring empty rooms, updating each room with the minimum distance to any gate encountered so far. Time: O(m * n * g) · Space: O(m * n) Code class Solution : def wallsAndGates ( self , rooms : List [ List [ int ]]) -> None : if not rooms : return rows , cols = len ( rooms ), len ( rooms [ 0 ]) gates = [( i , j ) for i in range ( rows ) for j in range ( cols ) if rooms [ i ][ j ] == 0 ] directions = [( 1 , 0 ), ( - 1 , 0 ), ( 0 , 1 ), ( 0 , - 1 )] for gate_row , gate_col in gates : visited = set () # To track visited cells in BFS queue = deque ([( gate_row , gate_col , 0 )]) while queue : row , col , distance = queue . popleft () rooms [ row ][ col ] = min ( rooms [ row ][ col ], distanc

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles