code.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Point struct {
  9. x, y int
  10. value byte
  11. }
  12. func (p *Point) key() string {
  13. return fmt.Sprintf("%d_%d", p.x, p.y)
  14. }
  15. func readInput(file *os.File) [][]byte {
  16. scanner := bufio.NewScanner(file)
  17. var matrix [][]byte
  18. for scanner.Scan() {
  19. line := scanner.Text()
  20. if line == "" {
  21. break
  22. }
  23. matrix = append(matrix, []byte(line))
  24. }
  25. return matrix
  26. }
  27. var directions [][]int = [][]int{
  28. {0, -1}, {1, 0}, {0, 1}, {-1, 0},
  29. }
  30. func getMoves(reindeer Point, matrix [][]byte, xMax, yMax int) []Point {
  31. var moves []Point
  32. for _, direction := range directions {
  33. move := Point{x: reindeer.x + direction[0], y: reindeer.y + direction[1]}
  34. if move.x >= 0 && move.x < xMax &&
  35. move.y >= 0 && move.y < yMax && matrix[move.y][move.x] > reindeer.value {
  36. move.value = matrix[move.y][move.x]
  37. moves = append(moves, move)
  38. }
  39. }
  40. return moves
  41. }
  42. func hike(reindeer Point, matrix [][]byte, xMax, yMax int) int {
  43. var nines int
  44. visited := make(map[string]bool)
  45. moves := []Point{reindeer}
  46. for len(moves) > 0 {
  47. current := moves[0]
  48. moves = moves[1:]
  49. if matrix[current.y][current.x] == '9' && !visited[current.key()] {
  50. nines++
  51. }
  52. newMoves := getMoves(current, matrix, xMax, yMax)
  53. for _, newMove := range newMoves {
  54. if !visited[newMove.key()] {
  55. moves = append(moves, newMove)
  56. visited[newMove.key()] = true
  57. }
  58. }
  59. }
  60. return nines
  61. }
  62. func part1(matrix [][]byte) int {
  63. var result int
  64. xMax := len(matrix[0])
  65. yMax := len(matrix)
  66. for y := range matrix {
  67. for x := range matrix[y] {
  68. if matrix[y][x] == '0' {
  69. reindeer := Point{x: x, y: y, value: '0'}
  70. result += hike(reindeer, matrix, xMax, yMax)
  71. }
  72. }
  73. }
  74. return result
  75. }
  76. func main() {
  77. if len(os.Args) < 2 {
  78. log.Fatal("You need to specify a file!")
  79. }
  80. filePath := os.Args[1]
  81. file, err := os.Open(filePath)
  82. if err != nil {
  83. log.Fatalf("Failed to open %s!\n", filePath)
  84. }
  85. matrix := readInput(file)
  86. fmt.Println("Part1:", part1(matrix))
  87. }