Problem Solving with Go course

GridsNeighbours and the Edge of the Grid

Problem Solving with Go

Display

Theme

Grids · Test exercise

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.

  1. 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}.
  2. Complete treesAround(grid []string, r, c int) int: how many of the eight cells around (r, c) are T. The cell (r, c) itself doesn't count.
  3. Complete crowded(grid []string) int: how many trees have at least 4 other trees around them.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// Offsets as {row, column}: up, down, left, right.
var dirs4 = [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// The four above plus the four diagonals.
var dirs8 = [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}

// inBounds reports whether row r, column c is inside the grid.
func inBounds(grid []string, r, c int) bool {
	return r >= 0 && r < len(grid) && c >= 0 && c < len(grid[r])
}

// neighbours4 returns the cells up, down, left and right of (r, c) that are
// inside the grid, in that order, as {row, column}.
func neighbours4(grid []string, r, c int) [][2]int {
	// TODO: loop over dirs4 and keep the cells that are inBounds
	return nil
}

// treesAround counts the 'T' cells among the eight cells around (r, c).
func treesAround(grid []string, r, c int) int {
	// TODO
	return 0
}

// crowded counts the trees with at least 4 trees around them.
func crowded(grid []string) int {
	// TODO
	return 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	grid := strings.Split(strings.TrimSpace(string(data)), "\n")
	fmt.Println("neighbours of the top-left corner:", neighbours4(grid, 0, 0))
	fmt.Println("crowded trees:", crowded(grid))
}
Go runtime not loaded yet

5 lines · 45 B of the 1 MB limit. Submit always uses the lesson's own input.