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. Keep the four moves in two small arrays and check each neighbour is inside the grid before using it.
Grid problems in the Graphs topic all start like this.
1int[] dr = {-1, 1, 0, 0};2int[] dc = {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}