Sub topic 7
Grids and neighbors: bounds checking
This chapter assumes you can index a nested list with grid[r][c], write nested for loops, and use a generator with yield. Many grid problems, such as flood fill, path finding, and cell counting, share one step: visit the cells next to a given cell. This chapter shows how to do that without index errors.
The neighbor pattern
A cell at row r and column c has four orthogonal neighbors: up, down, left, and right. You can describe each one as a pair of offsets (dr, dc) added to the current position.
| Direction | dr | dc |
|---|---|---|
| Up | -1 | 0 |
| Down | 1 | 0 |
| Left | 0 | -1 |
| Right | 0 | 1 |
Keeping the offsets in a tuple lets one loop handle all four directions. Adding four more pairs, such as (-1, -1), gives the diagonal neighbors too.
Why bounds checking matters
Cells on an edge or in a corner have fewer than four neighbors. If you compute a neighbor position and use it without checking, two different errors can occur:
- A row or column past the end, such as
grid[2]in a 2-row grid, raisesIndexError. - A negative index does not raise an error. In Python,
grid[-1]means the last row, so a cell at the top edge appears to have a neighbor on the bottom edge. The program runs and gives wrong answers.
The second error is more dangerous because nothing signals it.
A safe neighbor function
The check must test the row and the column against their own limits. This function does that and yields only valid positions.
def neighbors(grid, r, c):
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[nr]):
yield nr, nc
grid = [[1, 2, 3], [4, 5, 6]]
print(list(neighbors(grid, 0, 0))) # [(1, 0), (0, 1)]The corner cell (0, 0) has only two valid neighbors. The positions (-1, 0) and (0, -1) fail the 0 <= test and are skipped.
Two details are worth noting:
- Python's chained comparison
0 <= nr < len(grid)checks both limits in one expression. - The column check uses
len(grid[nr]), the length of the neighbor's row, and notlen(grid[0]). This also works for jagged grids whose rows differ in length. The row test comes first, andandshort-circuits, sogrid[nr]is only read whennris valid.
Using the neighbors
Once the check lives in one function, the rest of your code stays simple. This example sums the values around a cell.
def neighbors(grid, r, c):
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[nr]):
yield nr, nc
grid = [[1, 2, 3], [4, 5, 6]]
def neighbor_sum(grid, r, c):
return sum(grid[nr][nc] for nr, nc in neighbors(grid, r, c))
print(neighbor_sum(grid, 0, 1)) # 1 + 3 + 5 = 9Common mistakes
- Checking only the upper bound. Negative indices then wrap around.
- Swapping the limits, such as comparing
nrto the number of columns. This fails on grids that are not square. - Reading
grid[nr][nc]before the check, which raisesIndexError. - Testing the original
randcinstead of the newnrandnc.
Exercise
In a 3-row, 4-column grid, which neighbors does neighbors(grid, 2, 3) yield, and in what order? Assume the offset order up, down, left, right.
Show answer
The cell is the bottom-right corner. Up gives (1, 3), which is valid. Down gives (3, 3), which fails the row check. Left gives (2, 2), which is valid. Right gives (2, 4), which fails the column check. The result is [(1, 3), (2, 2)].
Exercise
Extend the offsets so neighbors also returns diagonal neighbors. How many neighbors does an interior cell have then?
Show answer
Add the four offsets (-1, -1), (-1, 1), (1, -1), and (1, 1) to the tuple. The bounds check stays the same. An interior cell has 8 neighbors.