Neighbours and the Edge of the Grid
Nearly every grid puzzle asks about neighbours: which cells you can reach in one step from here, or how many cells around here hold something.
Directions as data
Instead of writing four (or eight) similar ifs, store the directions as a list of {row, column} offsets:
var dirs4 = [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} // up, down, left, right
for _, d := range dirs4 {
nr, nc := r+d[0], c+d[1]
// (nr, nc) is a neighbour of (r, c)
}
Four-way (orthogonal) neighbours are for moves such as walking through a maze. Eight-way neighbours add the four diagonals ({-1, -1}, {-1, 1}, {1, -1}, {1, 1}) and are often used for "the cells around". Read the puzzle carefully: the answers differ a lot.
[2]int is a fixed-size array, not a slice. Arrays can be compared with == and can be map keys, which comes in handy in the next lesson.
The edge of the grid
Cells on the edge have fewer neighbours. Accessing grid[-1] or grid[r][len(grid[r])] panics, so check first:
func inBounds(grid []string, r, c int) bool {
return r >= 0 && r < len(grid) && c >= 0 && c < len(grid[r])
}
The order of the checks matters: r is checked before grid[r] is used. The && operator stops at the first false condition, so len(grid[r]) is never evaluated for a row that doesn't exist.
Task
This lesson's input is an orchard plan: T is a tree and . is grass. dirs4, dirs8 and inBounds are ready.
- Complete
neighbours4(grid []string, r, c int) [][2]int: the cells up, down, left and right of(r, c)that are inside the grid, in that order, as{row, column}. - Complete
treesAround(grid []string, r, c int) int: how many of the eight cells around(r, c)areT. The cell(r, c)itself doesn't count. - Complete
crowded(grid []string) int: how many trees have at least 4 other trees around them.