Problem Solving with Go course

Capstone PuzzlesGreenhouse, Part 1

Problem Solving with Go

Display

Theme

Capstone Puzzles · Test exercise

Greenhouse, Part 1

The last chapter is a set of puzzles in two parts, the way many puzzle sites serve them. Each one mixes ideas from earlier chapters, and the lessons no longer say which. Read the puzzle, work out what it really asks, and pick your tools. Part 2 always reuses your part 1 code.

The puzzle

A greenhouse keeper has laid out her beds on a grid. . is soil, ~ is peat, # is a paved path, and S is a sprinkler head. At minute 0 she opens the main tap, and every sprinkler wets its own cell. From then on, every minute, the water spreads from each wet cell to the cells directly up, down, left and right of it. Paving stops the water; soil and peat both let it through.

S.#.      0 1 # .
..#.  →   1 2 # .
###.      # # # .

In this small bed, the last cell to get wet is wet after 2 minutes, and the three cells on the right stay dry: no water can reach them past the paving.

The keeper wants to know two numbers for her whole greenhouse (this lesson's input): how many minutes until every cell the water can reach is wet, and how many soil or peat cells stay dry for good.

Task

Complete wetAfter(grid []string) (minutes, dry int). minutes is the minute the last reachable cell gets wet (0 if only the sprinklers are wet). dry counts the cells that aren't # and never get wet. The sprinkler cells themselves count as wet from minute 0.

Run your program on the input to see your part 1 answer, then submit.

main.go
package main

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

// Point is a cell: Row grows downwards, Col grows to the right.
type Point struct {
	Row, Col int
}

// Up, down, left, right.
var dirs = []Point{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// wetAfter returns how many minutes pass until every cell the water can reach is wet,
// and how many soil or peat cells stay dry. Water starts on every 'S' at minute 0 and
// spreads up, down, left and right by one cell a minute; it doesn't cross '#'.
func wetAfter(grid []string) (minutes, dry int) {
	// TODO
	return 0, 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(strings.ReplaceAll(string(data), "\r\n", "\n")), "\n")
	minutes, dry := wetAfter(grid)
	fmt.Println("part 1:", minutes, "minutes,", dry, "cells stay dry")
}
Go runtime not loaded yet

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