code.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. // Base case: we've matched all characters of the word
  27. if wordIndex == len(word) {
  28. if !found[wordSoFar] {
  29. found[wordSoFar] = true
  30. count++
  31. }
  32. return
  33. }
  34. // Check if the current position is valid
  35. if i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j] != word[wordIndex] {
  36. return
  37. }
  38. wordSoFar = fmt.Sprintf("%s%d_%d%c", wordSoFar, i, j, matrix[i][j])
  39. // Move to the next character in the word
  40. dfs(i+1, j, wordIndex+1, wordSoFar) // Down
  41. dfs(i-1, j, wordIndex+1, wordSoFar) // Up
  42. dfs(i, j+1, wordIndex+1, wordSoFar) // Right
  43. dfs(i, j-1, wordIndex+1, wordSoFar) // Left
  44. dfs(i+1, j+1, wordIndex+1, wordSoFar) // Diagonal down-right
  45. dfs(i-1, j-1, wordIndex+1, wordSoFar) // Diagonal up-left
  46. dfs(i+1, j-1, wordIndex+1, wordSoFar) // Diagonal down-left
  47. dfs(i-1, j+1, wordIndex+1, wordSoFar) // Diagonal up-right
  48. }
  49. // Try each cell as a starting point
  50. for i := 0; i < rows; i++ {
  51. for j := 0; j < cols; j++ {
  52. if matrix[i][j] == word[0] {
  53. dfs(i, j, 0, "")
  54. }
  55. }
  56. }
  57. fmt.Println(found)
  58. return count
  59. }
  60. func main() {
  61. if len(os.Args) < 2 {
  62. log.Fatal("You need to specify a file!")
  63. }
  64. filePath := os.Args[1]
  65. file, err := os.Open(filePath)
  66. if err != nil {
  67. log.Fatalf("Failed to open %s!\n", filePath)
  68. }
  69. matrix := readInput(file)
  70. fmt.Println("Part1:", countWordOccurrences(matrix, "XMAS"))
  71. }