code.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Point struct {
  9. y, x int
  10. value byte
  11. }
  12. func (p *Point) key() string {
  13. return fmt.Sprintf("%d_%d", p.y, p.x)
  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 == 1 {
  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, oneWay bool) 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' {
  50. nines++
  51. }
  52. newMoves := getMoves(current, matrix, xMax, yMax)
  53. for _, newMove := range newMoves {
  54. if oneWay {
  55. if !visited[newMove.key()] {
  56. moves = append(moves, newMove)
  57. visited[newMove.key()] = true
  58. }
  59. } else {
  60. moves = append(moves, newMove)
  61. }
  62. }
  63. }
  64. return nines
  65. }
  66. func solve(matrix [][]byte, oneWay bool) int {
  67. var result int
  68. xMax := len(matrix[0])
  69. yMax := len(matrix)
  70. for y := range matrix {
  71. for x := range matrix[y] {
  72. if matrix[y][x] == '0' {
  73. reindeer := Point{x: x, y: y, value: '0'}
  74. result += hike(reindeer, matrix, xMax, yMax, oneWay)
  75. }
  76. }
  77. }
  78. return result
  79. }
  80. func main() {
  81. if len(os.Args) < 2 {
  82. log.Fatal("You need to specify a file!")
  83. }
  84. filePath := os.Args[1]
  85. file, err := os.Open(filePath)
  86. if err != nil {
  87. log.Fatalf("Failed to open %s!\n", filePath)
  88. }
  89. matrix := readInput(file)
  90. fmt.Println("Part1:", solve(matrix, true))
  91. fmt.Println("Part2:", solve(matrix, false))
  92. }