Grade 12 Computer Science · Two-dimensional arrays
Neighbours and borders
The pattern most often got wrong, and how it is solved once.
Code that crashes on the very first cell
Code that counts, for every cell, how many full neighbors it has works perfectly on every cell in the middle of the grid. But it never even reaches the second cell: it fails on the first one. Why exactly there, and how can you arrange for there to be no edge at all?
Many questions about a grid concern a cell’s neighbours: how many full neighbours it has, what the average around it is, whether it matches whoever is beside it. The pattern is simple to explain and full of details people fall on, and all of them concern the cells at the edge.
int count = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue; // not itself
int nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= grid.length) continue;
if (nc < 0 || nc >= grid[nr].length) continue;
if (grid[nr][nc] != 0) count++;
}
}Why the two small loops are preferable
The eight neighbours can be written as eight explicit lines, and that is what most people try first. The two-small-loops form is preferable for three reasons: the range check is written once instead of eight times, it is easy to extend to a larger radius by changing two numbers, and it is far harder to forget one neighbour. The only detail to remember is skipping the cell itself — and it is exactly the first line in the body.
| The way | The range check | Easy to extend |
|---|---|---|
| Eight explicit lines | Eight times | No |
| Two small loops | Once | Yes |
| An added border | Not required | Yes |
Example 1 — how many neighbours a corner has
- Two directions are entirely blocked.
- Only three neighbours remain.
- And five positions out of range.
Example 2 — what the border does
- A cell is added on each side.
- Every real cell is in the middle.
- And there is no edge to check.