code.go 1.7 KB

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