Skip to content

Moving around a grid

Read · 1 of 3

Four directions, one loop

From (r, c) the neighbours are one step up, down, left and right. Loop over the four changes, and check each neighbour is inside the grid before using it.

Grid problems in the Graphs topic all start like this.

1for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
2 nr, nc = r + dr, c + dc
3 if 0 <= nr < R and 0 <= nc < C:
4 pass # (nr, nc) is a real neighbour