code.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. func countWordOccurrences(matrix [][]byte, word string) int {
  21. rows, cols := len(matrix), len(matrix[0])
  22. count := 0
  23. found := make(map[string]bool)
  24. var dfs func(i, j, wordIndex int, wordSoFar string)
  25. dfs = func(i, j, wordIndex int, wordSoFar string) {
  26. if wordIndex == len(word) {
  27. if !found[wordSoFar] {
  28. found[wordSoFar] = true
  29. count++
  30. }
  31. return
  32. }
  33. if i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j] != word[wordIndex] {
  34. return
  35. }
  36. wordSoFar = fmt.Sprintf("%s%d_%d%c", wordSoFar, i, j, matrix[i][j])
  37. dfs(i+1, j, wordIndex+1, wordSoFar) // Down
  38. dfs(i-1, j, wordIndex+1, wordSoFar) // Up
  39. dfs(i, j+1, wordIndex+1, wordSoFar) // Right
  40. dfs(i, j-1, wordIndex+1, wordSoFar) // Left
  41. dfs(i+1, j+1, wordIndex+1, wordSoFar) // Diagonal down-right
  42. dfs(i-1, j-1, wordIndex+1, wordSoFar) // Diagonal up-left
  43. dfs(i+1, j-1, wordIndex+1, wordSoFar) // Diagonal down-left
  44. dfs(i-1, j+1, wordIndex+1, wordSoFar) // Diagonal up-right
  45. }
  46. for i := 0; i < rows; i++ {
  47. for j := 0; j < cols; j++ {
  48. if matrix[i][j] == word[0] {
  49. dfs(i, j, 0, "")
  50. }
  51. }
  52. }
  53. fmt.Println(found)
  54. return count
  55. }
  56. func main() {
  57. if len(os.Args) < 2 {
  58. log.Fatal("You need to specify a file!")
  59. }
  60. filePath := os.Args[1]
  61. file, err := os.Open(filePath)
  62. if err != nil {
  63. log.Fatalf("Failed to open %s!\n", filePath)
  64. }
  65. matrix := readInput(file)
  66. fmt.Println("Part1:", countWordOccurrences(matrix, "XMAS"))
  67. }