123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- package main
- import (
- "bufio"
- "fmt"
- "log"
- "os"
- )
- type Point struct {
- x, y int
- value byte
- }
- func (p *Point) key() string {
- return fmt.Sprintf("%d_%d", p.x, p.y)
- }
- func readInput(file *os.File) [][]byte {
- scanner := bufio.NewScanner(file)
- var matrix [][]byte
- for scanner.Scan() {
- line := scanner.Text()
- if line == "" {
- break
- }
- matrix = append(matrix, []byte(line))
- }
- return matrix
- }
- var directions [][]int = [][]int{
- {0, -1}, {1, 0}, {0, 1}, {-1, 0},
- }
- func getMoves(reindeer Point, matrix [][]byte, xMax, yMax int) []Point {
- var moves []Point
- for _, direction := range directions {
- move := Point{x: reindeer.x + direction[0], y: reindeer.y + direction[1]}
- if move.x >= 0 && move.x < xMax &&
- move.y >= 0 && move.y < yMax && matrix[move.y][move.x] > reindeer.value {
- move.value = matrix[move.y][move.x]
- moves = append(moves, move)
- }
- }
- return moves
- }
- func hike(reindeer Point, matrix [][]byte, xMax, yMax int) int {
- var nines int
- visited := make(map[string]bool)
- moves := []Point{reindeer}
- for len(moves) > 0 {
- current := moves[0]
- moves = moves[1:]
- if matrix[current.y][current.x] == '9' && !visited[current.key()] {
- nines++
- }
- newMoves := getMoves(current, matrix, xMax, yMax)
- for _, newMove := range newMoves {
- if !visited[newMove.key()] {
- moves = append(moves, newMove)
- visited[newMove.key()] = true
- }
- }
- }
- return nines
- }
- func part1(matrix [][]byte) int {
- var result int
- xMax := len(matrix[0])
- yMax := len(matrix)
- for y := range matrix {
- for x := range matrix[y] {
- if matrix[y][x] == '0' {
- reindeer := Point{x: x, y: y, value: '0'}
- result += hike(reindeer, matrix, xMax, yMax)
- }
- }
- }
- return result
- }
- func main() {
- if len(os.Args) < 2 {
- log.Fatal("You need to specify a file!")
- }
- filePath := os.Args[1]
- file, err := os.Open(filePath)
- if err != nil {
- log.Fatalf("Failed to open %s!\n", filePath)
- }
- matrix := readInput(file)
- fmt.Println("Part1:", part1(matrix))
- }
|