Python coding

Fewest steps through a maze

A maze is a non-empty list of equal-length strings where "." is open and "#" is a wall. You start at the top-left cell and want the bottom-right cell, moving one step up, down, left or right through open cells. Return the fewest steps needed, or -1 if the exit can't be reached (also when the start is a wall).

Besides the tests, one large input (a 43 × 41 maze) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_steps(["..",".."]) → 2
  • fewest_steps([".#.",".#.","..."]) → 4
  • fewest_steps([".#","#."]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every step costs the same, so this is a shortest path in an unweighted graph: use BFS, not DFS.

Hint 2

Queue (row, col, distance) in a deque, starting at (0, 0, 0). Mark a cell seen when you enqueue it; return the distance the first time the exit comes off the queue.

Solution and why it works
pythonO(R·C), R × C = grid size · O(R·C)
from collections import deque

def fewest_steps(grid: list[str]) -> int:
    rows, cols = len(grid), len(grid[0])
    if grid[0][0] == "#":
        return -1
    queue, seen = deque([(0, 0, 0)]), {(0, 0)}
    while queue:
        r, c, dist = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return dist
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            inside = 0 <= nr < rows and 0 <= nc < cols
            if inside and grid[nr][nc] == "." and (nr, nc) not in seen:
                seen.add((nr, nc))
                queue.append((nr, nc, dist + 1))
    return -1

BFS reaches cells in order of distance from the start, so the first time the exit comes off the queue, no shorter route exists. DFS finds an exit too, but not the shortest way: on an open 3×3 grid it can wander 8 steps instead of 4. Mark cells seen when you enqueue them, or a cell is queued once per neighbor, and use deque.popleft(): list.pop(0) is O(n) per pop.