A Grid from the Input
Maps, mazes, game boards, orchards: lots of puzzles hand you a grid of characters as input.
..#.......
.....##...
..S....#..
Every line is a row of the grid, and every character is a cell. The simplest way to store it is a slice of rows: []string or [][]byte.
Rows and columns
Pick one order and stick to it: row first, then column. grid[r][c] is the cell in row r (from the top, starting at 0) and column c (from the left, starting at 0).
rows := len(grid)
cols := len(grid[0])
cell := grid[2][2] // 'S'
Many grid bugs come from mixing up (x, y) and (row, column). When a puzzle talks about x and y, remember that x is the column and y is the row.
[]string or [][]byte?
Reading a cell is the same in both: grid[r][c] gives you one byte. The difference is that strings can't be changed. If you need to change cells (marking a path, simulating changes), use [][]byte:
row := []byte("..S..")
row[2] = '.'
Compare cells with a character literal in single quotes: grid[r][c] == '#'. For ASCII input, one character is one byte.
Check the shape
Puzzle grids are almost always rectangles. If a row is shorter, something usually went wrong while reading the input: spaces at the end of a line, a \r from Windows, or a blank line at the end of the file. Checking the widths up front saves a lot of bug hunting.
Task
This lesson's input is a harbour map: . is water, # is a rock, S is the ship and H is the dock.
- Complete
parseGrid(input string) ([][]byte, error). Replace\r\nwith\n, drop spaces and blank lines at both ends withstrings.TrimSpace, then split into lines. Return an error if the input is empty or if any row's width differs from the first row's. - Complete
find(grid [][]byte, ch byte) (row, col int, ok bool): the position of the firstch, reading left to right and top to bottom. - Complete
count(grid [][]byte, ch byte) int: the number of cells holdingch.