From 0338b14930f3a7bebeb934b6d3e9be57a3fc2c43 Mon Sep 17 00:00:00 2001 From: Gregory Date: Tue, 22 Feb 2022 01:54:17 +0200 Subject: [PATCH] refactor d9 --- d9/common.go | 7 ++++--- d9/p2.go | 37 ++++++++++++------------------------- 2 files changed, 16 insertions(+), 28 deletions(-) diff --git a/d9/common.go b/d9/common.go index e7ed252..7e46fa1 100644 --- a/d9/common.go +++ b/d9/common.go @@ -5,11 +5,12 @@ import ( "strings" ) +const wall = '9' + func addWalls(lines []string) []string { for i, line := range lines { - lines[i] = fmt.Sprintf("9%v9", line) + lines[i] = fmt.Sprintf("%v%v%v", string(wall), line, string(wall)) } - - nines := strings.Repeat("9", len(lines[0])) + nines := strings.Repeat(string(wall), len(lines[0])) return append([]string{nines}, append(lines, nines)...) } diff --git a/d9/p2.go b/d9/p2.go index 57088c1..019614a 100644 --- a/d9/p2.go +++ b/d9/p2.go @@ -5,54 +5,41 @@ import ( "strings" ) -type exists struct{} - type pos struct { x int y int } -type basin map[pos]exists +type basin map[pos]bool -const wall = '9' - -func flooded(x, y int, basins []basin) bool { - for _, basin := range basins { - if _, ok := basin[pos{x, y}]; ok { - return true - } - } - - return false -} - -func flood(x, y int, heights []string, basin basin) basin { +func flood(x, y int, heights []string, basin basin, flooded basin) basin { if heights[y][x] == wall { return basin } - if _, ok := basin[pos{x, y}]; ok { + if flooded[pos{x, y}] { return basin } - basin[pos{x, y}] = exists{} + 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) - flood(x, y-1, heights, basin) - flood(x+1, y, heights, basin) - flood(x, y+1, heights, basin) - flood(x-1, y, heights, basin) return basin } func P2(in string) int { heights := addWalls(strings.Split(strings.TrimSpace(in), "\n")) basins := []basin{} + flooded := basin{} for y := 1; y < len(heights)-1; y++ { for x := 1; x < len(heights[0])-1; x++ { - if !flooded(x, y, basins) && heights[y][x] != wall { - basins = append(basins, flood(x, y, heights, basin{})) - } + basins = append(basins, flood(x, y, heights, basin{}, flooded)) } }