VISUALGO//PROBLEMS
nearest exit from entrance in maze · graphs – bfsmedium
grid
0
step
·
answer
·
queue
·
ELEMENTS
maze
entrance
Python
from collections import deque
def nearestExit(maze: list[list[str]], entrance: list[int]) -> int:
rows, cols = len(maze), len(maze[0])
start = (entrance[0], entrance[1])
seen = {start}
queue = deque([start])
steps = 0
while queue:
steps += 1
for _ in range(len(queue)):
r, c = queue.popleft()
for y, x in ((r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)):
if 0 <= y < rows and 0 <= x < cols and maze[y][x] == '.' and (y, x) not in seen:
if y in (0, rows - 1) or x in (0, cols - 1):
return steps
seen.add((y, x))
queue.append((y, x))
return -1