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) {
wetAt := map[Point]int{}
var queue []Point
for r, row := range grid {
for c := 0; c < len(row); c++ {
if row[c] == 'S' {
p := Point{r, c}
wetAt[p] = 0
queue = append(queue, p)
}
}
}
for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
minutes = max(minutes, wetAt[cur])
for _, d := range dirs {
next := Point{cur.Row + d.Row, cur.Col + d.Col}
if next.Row < 0 || next.Row >= len(grid) || next.Col < 0 || next.Col >= len(grid[next.Row]) ||
grid[next.Row][next.Col] == '#' {
continue
}
if _, seen := wetAt[next]; !seen {
wetAt[next] = wetAt[cur] + 1
queue = append(queue, next)
}
}
}
for r, row := range grid {
for c := 0; c < len(row); c++ {
if _, wet := wetAt[Point{r, c}]; !wet && row[c] != '#' {
dry++
}
}
}
return minutes, dry
}
// soak is a cell and the minute it gets wet.
type soak struct {
at Point
minutes int
}
// soakQueue is a priority queue for container/heap: Pop gives the earliest minute.
type soakQueue []soak
func (q soakQueue) Len() int { return len(q) }
func (q soakQueue) Less(i, j int) bool { return q[i].minutes < q[j].minutes }
func (q soakQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *soakQueue) Push(x any) { *q = append(*q, x.(soak)) }
func (q *soakQueue) Pop() any {
old := *q
s := old[len(old)-1]
*q = old[:len(old)-1]
return s
}
// wetAfterPeat is wetAfter where water needs 3 minutes to soak into a peat cell '~'
// instead of 1. Every other cell still takes 1 minute.
func wetAfterPeat(grid []string) (minutes, dry int) {
// TODO: the same spread, but the earliest wet cell first: Dijkstra with soakQueue
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")
minutes, dry = wetAfterPeat(grid)
fmt.Println("part 2:", minutes, "minutes,", dry, "cells stay dry")
}