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 moves and check each neighbour is inside the grid before using it.

Grid problems in the Graphs topic all start like this.

1for (const [dr, dc] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) {
2 const nr = r + dr, nc = c + dc;
3 if (nr >= 0 && nr < R && nc >= 0 && nc < C) {
4 // (nr, nc) is a real neighbour
5 }
6}