Sub topic 4
Writing a Neighbour Function
This chapter assumes you know Python lists, tuples, sets, and generators, and that you have seen a grid treated as a graph where each cell is a vertex. Here you write the one function that turns a grid into a graph: the neighbour function.
What the function does
A neighbour function takes a cell and returns the cells you can reach in one move. The search algorithms in later chapters call it instead of reading a stored edge list. The grid itself is the graph, and this function supplies its edges on demand.
Three decisions go into it:
- Which directions count as a move (connectivity).
- Which cells lie outside the grid (bounds).
- Which cells you may not enter (obstacles).
The function
def neighbors(grid, r, c, diagonal=False):
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if diagonal:
steps += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in steps:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != '#':
yield nr, ncThe list steps holds row and column offsets. Adding an offset to (r, c) gives a candidate cell. The if statement keeps only candidates that are inside the grid and not a wall ('#'). The function uses yield, so it returns a generator and produces cells one at a time.
Connectivity
With the default setting, a cell has up to four neighbours: up, down, left, and right. This is 4-connectivity. Setting diagonal=True adds four more offsets, which gives 8-connectivity.
grid = [
"..#",
".#.",
"...",
]
print(list(neighbors(grid, 1, 0)))
print(list(neighbors(grid, 1, 0, diagonal=True)))Cell (1, 0) has (0, 0) above it, (2, 0) below it, and a wall at (1, 1) to its right. The first call prints [(0, 0), (2, 0)]. The second call also finds the diagonal cell (2, 1). It skips (0, 1) only if that cell is a wall, and here (0, 1) is open, so the output is [(0, 0), (2, 0), (0, 1), (2, 1)].
Common errors
- Checking bounds after indexing. Writing
grid[nr][nc] != '#'before0 <= nr < len(grid)can raiseIndexError. Worse, a negative index such as-1does not fail in Python. It silently wraps to the opposite edge of the grid. Keep the bounds test first.andstops at the first false condition, so the wall check only runs on valid indices. - Using the wrong dimension. Rows come from
len(grid)and columns fromlen(grid[0]). Swapping them works on square grids and breaks on rectangular ones. - Forgetting that the start cell may be a wall. The function filters the cells you move into. It does not check the cell you stand on.
- Treating diagonal moves as free corner cuts. Some problems forbid a diagonal step between two walls. This version allows it. If your problem forbids it, add a check on the two orthogonal cells beside the diagonal.
Why a generator
Returning a list would also work. A generator avoids building a list you may only partly read. Callers can still use list(...) when they need all cells at once, as the example above does.
Exercise
A grid has 3 rows and 5 columns. A student writes the bounds check as 0 <= nr < len(grid[0]) and 0 <= nc < len(grid). What goes wrong?
Show answer
The row limit uses the column count (5) and the column limit uses the row count (3). The function would accept row 3 or 4, which do not exist, and raise an IndexError. It would also reject valid columns 3 and 4. The correct check is 0 <= nr < len(grid) and 0 <= nc < len(grid[0]).
Exercise
Modify neighbors so that a diagonal move is allowed only when both orthogonal cells beside it are open. Which cells do you test for a step of (-1, 1) from (r, c)?
Show answer
Test (r-1, c) and (r, c+1). Both must be inside the grid and not '#'. In general, for a step (dr, dc), test (r+dr, c) and (r, c+dc).