code.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. func readInput(file *os.File) [][]byte {
  9. scanner := bufio.NewScanner(file)
  10. var matrix [][]byte
  11. for scanner.Scan() {
  12. line := scanner.Text()
  13. if line == "" {
  14. break
  15. }
  16. matrix = append(matrix, []byte(line))
  17. }
  18. return matrix
  19. }
  20. var directions [][]int = [][]int{
  21. {0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1},
  22. }
  23. func checkPath(i, j int, matrix [][]byte, word string, index int, direction []int, rows, cols int) int {
  24. if i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j] != word[index] {
  25. return 0
  26. }
  27. if index == len(word)-1 {
  28. return 1
  29. }
  30. i += direction[0]
  31. j += direction[1]
  32. index++
  33. return checkPath(i, j, matrix, word, index, direction, rows, cols)
  34. }
  35. func check(i, j int, matrix [][]byte, word string, rows, cols int) int {
  36. var count int
  37. for _, direction := range directions {
  38. count += checkPath(i, j, matrix, word, 0, direction, rows, cols)
  39. }
  40. return count
  41. }
  42. func part1(matrix [][]byte, word string) int {
  43. var count int
  44. rows, cols := len(matrix), len(matrix[0])
  45. for i := 0; i < rows; i++ {
  46. for j := 0; j < cols; j++ {
  47. if matrix[i][j] == word[0] {
  48. count += check(i, j, matrix, word, rows, cols)
  49. }
  50. }
  51. }
  52. return count
  53. }
  54. func main() {
  55. if len(os.Args) < 2 {
  56. log.Fatal("You need to specify a file!")
  57. }
  58. filePath := os.Args[1]
  59. file, err := os.Open(filePath)
  60. if err != nil {
  61. log.Fatalf("Failed to open %s!\n", filePath)
  62. }
  63. matrix := readInput(file)
  64. fmt.Println("Part1:", part1(matrix, "XMAS"))
  65. }