aoc21/d9/p2.go

50 lines
933 B
Go
Raw Normal View History

2022-02-21 22:01:00 +02:00
package d9
import (
"sort"
"strings"
)
type pos struct {
x int
y int
}
2022-02-22 01:54:17 +02:00
type basin map[pos]bool
2022-02-21 22:01:00 +02:00
2022-02-22 01:54:17 +02:00
func flood(x, y int, heights []string, basin basin, flooded basin) basin {
2022-02-21 22:01:00 +02:00
if heights[y][x] == wall {
return basin
}
2022-02-22 01:54:17 +02:00
if flooded[pos{x, y}] {
2022-02-21 22:01:00 +02:00
return basin
}
2022-02-22 01:54:17 +02:00
basin[pos{x, y}] = true
flooded[pos{x, y}] = true
flood(x, y-1, heights, basin, flooded)
flood(x+1, y, heights, basin, flooded)
flood(x, y+1, heights, basin, flooded)
flood(x-1, y, heights, basin, flooded)
2022-02-21 22:01:00 +02:00
return basin
}
2022-02-21 22:28:30 +02:00
func P2(in string) int {
2022-02-21 22:01:00 +02:00
heights := addWalls(strings.Split(strings.TrimSpace(in), "\n"))
basins := []basin{}
2022-02-22 01:54:17 +02:00
flooded := basin{}
2022-02-21 22:01:00 +02:00
for y := 1; y < len(heights)-1; y++ {
for x := 1; x < len(heights[0])-1; x++ {
2022-02-22 01:54:17 +02:00
basins = append(basins, flood(x, y, heights, basin{}, flooded))
2022-02-21 22:01:00 +02:00
}
}
sort.Slice(basins, func(i, j int) bool { return len(basins[i]) > len(basins[j]) })
return len(basins[0]) * len(basins[1]) * len(basins[2])
}