def read_grid(filename): grid = [] with open(filename, 'r') as file: for line in file: grid.append(list(line.strip())) return grid def count_word_occurrences(grid, word): rows = len(grid) cols = len(grid[0]) word_length = len(word) count = 0 directions = [ (0, 1), # Right (1, 0), # Down (0, -1), # Left (-1, 0), # Up (1, 1), # Diagonal down-right (1, -1), # Diagonal down-left (-1, -1), # Diagonal up-left (-1, 1), # Diagonal up-right ] for x in range(rows): for y in range(cols): for dx, dy in directions: match = True for k in range(word_length): nx = x + dx * k ny = y + dy * k if 0 <= nx < rows and 0 <= ny < cols: if grid[nx][ny] != word[k]: match = False break else: match = False break if match: count += 1 return count # Main execution if __name__ == "__main__": grid = read_grid('input.txt') # grid = read_grid('example.txt') word = "XMAS" total_occurrences = count_word_occurrences(grid, word) print(total_occurrences)