code.go 2.1 KB

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