Skip to content

Commit ea987b6

Browse files
committed
2024.12 Simpler visit history
1 parent 1ef8b9f commit ea987b6

File tree

1 file changed

+7
-20
lines changed

1 file changed

+7
-20
lines changed

2024/12-garden/main.go

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,25 @@ import (
77
)
88

99
var grid [][]byte
10-
var history map[byte][]position
10+
var visited [][]bool
1111

1212
func main() {
1313
file := util.FileFromArgs()
1414
scan := bufio.NewScanner(file)
1515

1616
for scan.Scan() {
1717
grid = append(grid, scan.Bytes())
18+
visited = append(visited, make([]bool, len(grid[len(grid)-1])))
1819
}
1920

20-
history = map[byte][]position{}
2121
var area, perimeter, sum int
2222
for y := range grid {
2323
for x := range grid[y] {
2424
area, perimeter = measure(x, y)
2525
sum += area * perimeter
2626

2727
// Debug: print the found area
28-
if area > 0 {
28+
if area != 0 {
2929
fmt.Println(string(grid[y][x]), area, perimeter)
3030
}
3131
}
@@ -34,27 +34,14 @@ func main() {
3434
fmt.Println(sum)
3535
}
3636

37-
type position struct {
38-
X, Y int
39-
}
40-
4137
// measure returns the area and peremiter this position is part of
4238
func measure(x, y int) (int, int) {
43-
// Have we passed here yet?
44-
if _, exists := history[grid[y][x]]; exists {
45-
for i := range history[grid[y][x]] {
46-
if history[grid[y][x]][i].X == x && history[grid[y][x]][i].Y == y {
47-
return 0, 0
48-
}
49-
}
50-
51-
history[grid[y][x]] = append(history[grid[y][x]], position{x, y})
52-
} else {
53-
history[grid[y][x]] = []position{
54-
{x, y},
55-
}
39+
if visited[y][x] {
40+
return 0, 0
5641
}
5742

43+
visited[y][x] = true
44+
5845
// Measure shapes
5946
area, perimeter := 1, 0
6047
var dA, dP int

0 commit comments

Comments
 (0)