~xenrox/aoc2021

ref: 777f9de1c97225faed0b9aeedc7e3b3bdafcdd52 aoc2021/day09/main.go -rw-r--r-- 761 bytes
777f9de1Thorben Günther Solve day 9 part 1 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package day09

import (
	"fmt"
	"log"
)

func Run() {
	res, err := calc1("data/day09.dat")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Part 1: %d\n", res)
}

func calc1(path string) (int, error) {
	heightMap, err := readFile(path)
	if err != nil {
		return 0, err
	}
	var risk int

	// assume rectangle map form
	lenRow := len(heightMap[0])
	lenColumn := len(heightMap)

	for i, row := range heightMap {
		for j, point := range row {
			if ((i-1 >= 0 && point < heightMap[i-1][j]) || i == 0) &&
				((i+1 < lenColumn && point < heightMap[i+1][j]) || i == lenColumn-1) &&
				((j-1 >= 0 && point < heightMap[i][j-1]) || j == 0) &&
				((j+1 < lenRow && point < heightMap[i][j+1]) || j == lenRow-1) {
				risk += point + 1
			}
		}
	}

	return risk, nil
}