Many problems are posed on a grid (a list of strings or lists): mazes, maps, boards. They are traversed with recursion: from a cell, the neighbors are tried.
Moving around a grid
Moves are encoded as pairs (row change, column change) and you always check that you are inside the grid before looking at the cell.
grid = [
"S.#",
".#.",
"..E",
]
def inside(grid, r, c):
return 0 <= r < len(grid) and 0 <= c < len(grid[0])
print(inside(grid, 0, 0)) # True
print(inside(grid, 3, 0)) # False
print(grid[2][2]) # E
Counting paths
To go from top-left to bottom-right moving only right or down, the number of paths from a cell is the sum of those of the next two cells. It is a recursion that counts.
def count(grid, r, c):
if r >= len(grid) or c >= len(grid[0]) or grid[r][c] == "#":
return 0 # outside or wall: no path
if r == len(grid) - 1 and c == len(grid[0]) - 1:
return 1 # arrived: one path
return count(grid, r + 1, c) + count(grid, r, c + 1)
print(count(["...", ".#.", "..."], 0, 0)) # 2
print(count(["...", "...", "..."], 0, 0)) # 6
Practise with Paths in a grid. If the grid is large, this recursion repeats computations: storing the results (memoization), which you will see later in the complexity and efficiency lesson, would help there.
Filling a region (flood fill)
To count islands (groups of connected cells) each island is traversed entirely once, marking the visited cells so they are not counted twice. The four neighbors of each cell are visited.
def explore(grid, r, c, visited):
if r < 0 or c < 0 or r >= len(grid) or c >= len(grid[0]):
return 0
if grid[r][c] != "1" or (r, c) in visited:
return 0
visited.add((r, c))
return (1 + explore(grid, r + 1, c, visited) + explore(grid, r - 1, c, visited)
+ explore(grid, r, c + 1, visited) + explore(grid, r, c - 1, visited))
grid = ["1100", "1001", "0011", "0001"]
visited = set()
sizes = []
for r in range(len(grid)):
for c in range(len(grid[0])):
t = explore(grid, r, c, visited)
if t > 0:
sizes.append(t)
print(len(sizes), sizes) # 2 [3, 4]
Here the visited cells are not unmarked: we never want to go back to them. Unlike the queens backtracking, nothing has to be undone. You practise it in Count islands.
Escaping a maze
To find one path from the entrance to the exit the directions are tried in a fixed order. If from a cell no direction works, "no path" is returned and the caller tries the next direction: that is the backtracking.
MOVES = [("D", 1, 0), ("R", 0, 1), ("U", -1, 0), ("L", 0, -1)]
def search(grid, r, c, visited):
if grid[r][c] == "E":
return "" # arrived: empty path from here
visited.add((r, c))
for letter, dr, dc in MOVES:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]):
if grid[nr][nc] != "#" and (nr, nc) not in visited:
rest = search(grid, nr, nc, visited)
if rest is not None: # some branch succeeded
return letter + rest
return None # dead end
grid = ["S.#", ".#.", "..E"]
print(search(grid, 0, 0, set())) # DDRR
Notice that "" (the empty path on arrival) and None (there is no path) are different values: that is why you compare with is not None and not with if rest:. The path found need not be the shortest; for the shortest one you would use a breadth-first search. You practise it in Escape the maze.
Recursion limit
Python limits the depth of recursion (about 1 000 calls by default). In small grids it does not matter, but a 100 × 100 maze could exceed it. In that case you use an iterative traversal with a stack or a queue, as we saw with graphs, or raise the limit with sys.setrecursionlimit.