Question 6
Back to Exercise
Find the length of the shortest path from the top-left to the bottom-right of a grid ("." free, "#" wall), moving in four directions, and print the path drawn on the grid.
Solution
from collections import deque
def shortest(grid):
rows, cols = len(grid), len(grid[0])
start, goal = (0, 0), (rows - 1, cols - 1)
parent = {start: None}
queue = deque([start])
while queue:
r, c = queue.popleft()
if (r, c) == goal:
break
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "." and (nr, nc) not in parent:
parent[(nr, nc)] = (r, c)
queue.append((nr, nc))
if goal not in parent:
return -1, grid
path, cell = [], goal
while cell:
path.append(cell)
cell = parent[cell]
drawn = [list(row) for row in grid]
for r, c in path:
drawn[r][c] = "*"
return len(path) - 1, ["".join(row) for row in drawn]
steps, picture = shortest(["..#..",
".##.#",
"....."])
print(steps)
print("\n".join(picture))
6 *.#.. *##.# *****
BFS explores in order of distance, and the parent map lets us walk back from the goal to draw the path. O(rows × cols).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!