Grid Maze Shortest Path with A* Search
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests knowledge of informed graph search, admissible heuristics, priority-queue mechanics, and canonical path reconstruction on a 2-D grid.
Grid Maze Shortest Path with A* Search
You are given a rectangular grid of characters representing a maze. Each cell contains one of the following:
'.'— walkable open space'#'— a wall (impassable)'S'— the starting position (also walkable)'T'— the destination (also walkable)
From any cell you may step to an adjacent cell in one of four directions — up, down, left, or right — and every such step costs exactly 1. Diagonal moves are not allowed.
Task
Find a shortest path from S to T using the A* algorithm with the Manhattan distance as the heuristic. Return the result as a dictionary with two keys:
"distance"— the number of steps in the shortest path (an integer ≥ 0), or-1if no path exists."path"— the sequence of cells along that path, each cell represented as a two-element list[row, col](0-indexed, row 0 is the top row). The list starts withSand ends withT. Return an empty list when no path exists.
Path tie-breaking rule
Multiple shortest paths of equal length may exist. Among all shortest paths, return the lexicographically smallest one. A path P is lexicographically smaller than a path Q if, at the first position where they differ, P's cell [r1, c1] is smaller than Q's cell [r2, c2] — comparing row first, then column.
Failure conditions
Return {"distance": -1, "path": []} when:
- the grid is empty or any row has a different length from the others,
SorTis absent from the grid,- no path connects
StoT(e.g., the destination is fully surrounded by walls).
Constraints
1 ≤ m, n ≤ 100wheremis the number of rows andnis the number of columns.- Every row has the same length (the grid is rectangular).
- There is at most one
Sand at most oneTin the grid. SandTare distinct cells.- Only
'#'cells are impassable;'S','T', and'.'are all walkable.
Examples
Example 1
Input: find_maze_path(['S..', '.#.', '..T'])
Output: {'distance': 4, 'path': [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2]]}
Example 2
Input: find_maze_path(['S#.', '.#.', '..T'])
Output: {'distance': 4, 'path': [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2]]}
Example 3
Input: find_maze_path(['S', 'T'])
Output: {'distance': 1, 'path': [[0, 0], [1, 0]]}
Hints
Hint 1
The Manhattan distance |Δrow| + |Δcol| to the target is an admissible heuristic for 4-directional unit-cost movement — it never overestimates the true remaining steps because every step reduces at most one of those two absolute differences by 1.
Hint 2
A* with a consistent (monotone) heuristic guarantees that the first time a cell is popped from the priority queue its distance is already optimal, so you can skip any pop whose recorded cost no longer matches the best known distance — no decrease-key operation is needed.
Hint 3
To enforce the lexicographic tie-break, run a reverse BFS from T after A* finishes to compute the step-count from every reachable cell to T, then greedily reconstruct the path from S by always picking the smallest (row, col) neighbor whose distance-to-target is exactly one less than the current cell's.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has three distinct phases.
Phase 1 — A* forward search
A* is Dijkstra's algorithm steered toward the target by a heuristic estimate. Every open cell u carries two costs:
g(u): the exact cheapest distance fromStoufound so far.h(u): an estimate of the remaining distance toT.f(u) = g(u) + h(u): the estimated total path cost throughu.
The heap always expands the cell with the smallest f. The heuristic chosen here is Manhattan distance:
h(r, c) = |r − target_row| + |c − target_col|
This heuristic is admissible because every step changes exactly one coordinate by 1, so reaching T always takes at least |Δrow| + |Δcol| steps regardless of walls — h never overestimates.
It is also consistent: for any neighbor v of u, h(u) ≤ 1 + h(v), because one move shifts Manhattan distance by at most 1. Consistency means f values are non-decreasing along any path, so the first time a cell is popped from the heap its g is already optimal. Stale heap entries (pushed before a better distance was found) are discarded with a simple cost-equality check — no decrease-key operation is needed.
Phase 2 — Reverse BFS from T
A* produces optimal distances, but reconstructing a path from parent pointers is tricky when you need a specific tie-breaking rule. Instead, run a plain BFS backward from T to compute steps_to_target[cell] — the minimum steps from each reachable cell to T.
Any shortest path from S to T is a sequence of cells where steps_to_target decreases by exactly 1 at each step.
Phase 3 — Greedy lexicographic reconstruction
Walk forward from S. At each position, collect all four neighbors whose steps_to_target is one less than the current cell's (those are valid next steps on some shortest path), then pick the minimum by (row, col) order. Repeating this greedily builds the lexicographically smallest shortest path.
Why it is correct
- A* with a consistent heuristic guarantees
dist[target]is the true shortest distance. - Reverse BFS from
Tgives exact remaining distances for every cell on every shortest path. - The greedy forward reconstruction always has at least one valid candidate (since we confirmed a path exists), and choosing the smallest at each step produces the globally lexicographically smallest shortest path by induction.
Edge cases
- Empty grid or ragged rows → return failure immediately.
- Missing
SorT→ return failure. Tis unreachable (e.g., walled off) → the heap empties without poppingT;targetis absent fromdist; return failure.Sis directly adjacent toT→ distance 1, path is two cells.
Complexity
Let V = m × n.
- Time: O(V log V) — each cell is finalized at most once, each of its ≤ 4 edges triggers at most one heap push, and each heap operation costs O(log V). The reverse BFS is O(V).
- Space: O(V) — for
dist,steps_to_target, the heap, and the returned path.
Reference solution
import heapq
from collections import deque
from typing import List, Dict
def find_maze_path(grid: List[str]) -> Dict[str, object]:
if not grid or not grid[0]:
return {"distance": -1, "path": []}
rows = len(grid)
cols = len(grid[0])
if any(len(row) != cols for row in grid):
return {"distance": -1, "path": []}
start = target = None
for r in range(rows):
for c in range(cols):
if grid[r][c] == 'S':
start = (r, c)
elif grid[r][c] == 'T':
target = (r, c)
if start is None or target is None:
return {"distance": -1, "path": []}
def heuristic(cell):
return abs(cell[0] - target[0]) + abs(cell[1] - target[1])
directions = [(-1, 0), (0, -1), (0, 1), (1, 0)]
dist = {start: 0}
heap = [(heuristic(start), 0, start[0], start[1])]
while heap:
f, cost, r, c = heapq.heappop(heap)
cell = (r, c)
if cost != dist.get(cell):
continue
if cell == target:
break
for dr, dc in directions:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == '#':
continue
neighbor = (nr, nc)
new_cost = cost + 1
if new_cost < dist.get(neighbor, float('inf')):
dist[neighbor] = new_cost
heapq.heappush(heap, (new_cost + heuristic(neighbor), new_cost, nr, nc))
if target not in dist:
return {"distance": -1, "path": []}
shortest_distance = dist[target]
# Reverse BFS from T
steps_to_target = {target: 0}
queue = deque([target])
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
neighbor = (nr, nc)
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == '#' or neighbor in steps_to_target:
continue
steps_to_target[neighbor] = steps_to_target[(r, c)] + 1
queue.append(neighbor)
# Greedy lex-smallest path reconstruction
path = [list(start)]
current = start
while current != target:
r, c = current
candidates = [
(nr, nc)
for dr, dc in directions
for nr, nc in [(r + dr, c + dc)]
if steps_to_target.get((nr, nc)) == steps_to_target[current] - 1
]
current = min(candidates)
path.append(list(current))
return {"distance": shortest_distance, "path": path}