Skip to content
BytePatterns

Grid Traversal

Matrix & Grid: lesson 1 of 5

Row first, column second, and always check the edge.

Lesson 1 of 5 · 4 min

Grid Traversal

Step 1 of 10

A grid is a list of rows, so grid[r][c] is row r, column c — row first, every time.

The Idea

A grid is a list of rows, so grid[r][c] reads row r, column c. Row first, always.

Neighbours are offsets added to that pair: four for edge-sharing, eight if diagonals count. Each one needs the same guard, 0 <= r < rows and 0 <= c < cols, because Python answers a negative index with the far side of the grid instead of an error.

Real-World Example

A spreadsheet recalculates exactly this way. Changing one cell walks the neighbours that referenced it, and the app has to know the sheet's edges — otherwise a formula in row 1 would quietly pull its value from the bottom of the sheet.

The Code

grid = [[0, 1, 2, 3],
        [4, 5, 6, 7],
        [8, 9, 10, 11]]
rows, cols = len(grid), len(grid[0])
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]   # up, down, left, right

def neighbours(r, c):
    for dr, dc in DIRS:
        nr, nc = r + dr, c + dc
        if 0 <= nr < rows and 0 <= nc < cols:   # the guard, every time
            yield grid[nr][nc]

print(list(neighbours(1, 1)))   # [1, 9, 4, 6]
print(list(neighbours(0, 0)))   # [4, 1]  -> two offsets fell off the grid

Python

Your turn

Put the steps in the right order.

  1. Add the offset to the current row and column
  2. Take the next offset from the direction list
  3. Read the cell — it is safely inside the grid
  4. Reject the candidate unless both indexes are in range

Mini quiz

1 / 3

Which offset moves one cell up?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.