Matrices and grids · 3 / 15 Theory

Traversals: diagonals, neighbors and spiral

Many grid problems require moving between squares. The standard technique is to store the possible offsets in a list and always check the bounds before accessing.

DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]      # up, down, left, right

def neighbors(m, i, j):
    f, c = len(m), len(m[0])
    for di, dj in DIRECTIONS:
        ni, nj = i + di, j + dj
        if 0 <= ni < f and 0 <= nj < c:               # do not go past the edges
            yield ni, nj

m = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
print(list(neighbors(m, 0, 0)))                         # [(1, 0), (0, 1)]
print([m[i][j] for i, j in neighbors(m, 1, 1)])         # [2, 8, 4, 6]

n = len(m)
print([m[i][i] for i in range(n)])                    # [1, 5, 9]   main diagonal
print([m[i][n - 1 - i] for i in range(n)])            # [3, 5, 7]   secondary diagonal

for d in range(-2, 3):                                # diagonals parallel to the main one
    print(d, [m[i][i + d] for i in range(n) if 0 <= i + d < n])   # -2 [7]  -1 [4, 8] ...

Spiral traversal

A compact trick: remove the first row and rotate the rest counterclockwise, so that the next edge ends up on top. Repeat until nothing is left.

m = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
result = []
while m:
    result += m.pop(0)
    m = list(zip(*m))[::-1]
print(result)        # [1, 2, 3, 6, 9, 8, 7, 4, 5]
  • For 8 neighbors (as in minesweeper) loop di and dj over (-1, 0, 1) excluding (0, 0).
  • 0 <= ni < r avoids out-of-range indexes; beware of negatives, which in Python do not fail but count from the end.
  • On the diagonal i + j == k elements are numbered by adding indexes; on i - j == k, by subtracting them.

You practice it in Diagonals of a matrix, Spiral traversal and Minesweeper.