Moving around a grid
Read · 1 of 4
Four directions, one loop
From cell (r, c), the neighbours are (r − 1, c), (r + 1, c), (r, c − 1) and (r, c + 1). Keep the changes in two small arrays and loop over them:
Always check a neighbour is inside the grid (0 ≤ row < R and 0 ≤ column < C) before using it. Grid problems in the Graphs topic all start like this.
1int dr[4] = {-1, 1, 0, 0};2int dc[4] = {0, 0, -1, 1};3for (int k = 0; k < 4; k++) {4 int nr = r + dr[k], nc = c + dc[k];5 if (nr >= 0 && nr < R && nc >= 0 && nc < C) {6 // (nr, nc) is a real neighbour7 }8}