code.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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, xMax, yMax int) []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 move.x >= 0 && move.x < xMax &&
  54. move.y >= 0 && move.y < yMax && matrix[move.y][move.x] != '#' {
  55. if reindeer.direction[0] == direction[0] && reindeer.direction[1] == direction[1] {
  56. move.cost++
  57. } else {
  58. move.cost += 1000
  59. }
  60. moves = append(moves, move)
  61. }
  62. }
  63. return moves
  64. }
  65. func hike(reindeer *Point, matrix [][]byte, xMax, yMax int) int {
  66. cost := 1000000000
  67. visited := make(map[string]int)
  68. moves := []Point{*reindeer}
  69. for len(moves) > 0 {
  70. current := moves[0]
  71. moves = moves[1:]
  72. if matrix[current.y][current.x] == 'E' && current.cost < cost {
  73. cost = current.cost
  74. }
  75. newMoves := getMoves(current, matrix, xMax, yMax)
  76. for _, newMove := range newMoves {
  77. if visited[newMove.key()] == 0 || visited[newMove.key()] > newMove.cost {
  78. moves = append(moves, newMove)
  79. visited[newMove.key()] = newMove.cost
  80. }
  81. }
  82. }
  83. return cost
  84. }
  85. func main() {
  86. if len(os.Args) < 2 {
  87. log.Fatal("You need to specify a file!")
  88. }
  89. filePath := os.Args[1]
  90. file, err := os.Open(filePath)
  91. if err != nil {
  92. log.Fatalf("Failed to open %s!\n", filePath)
  93. }
  94. reindeer, matrix := readInput(file)
  95. fmt.Println("Part1:", hike(reindeer, matrix, len(matrix[0]), len(matrix)))
  96. }