def read_input(file): with open(file, 'r') as f: return [line.strip() for line in f.readlines()] def count_xmas(grid): directions = [ (0, 1), (0, -1), (1, 0), (-1, 0), # right, left, down, up (1, 1), (1, -1), (-1, 1), (-1, -1) # diagonals: down-right, down-left, up-right, up-left ] word = "XMAS" count = 0 rows, cols = len(grid), len(grid[0]) for r in range(rows): for c in range(cols): for dr, dc in directions: if all(0 <= r + i * dr < rows and 0 <= c + i * dc < cols and grid[r + i * dr][c + i * dc] == word[i] for i in range(len(word))): count += 1 return count def count_x_mas(grid): count = 0 rows, cols = len(grid), len(grid[0]) for r in range(1, rows - 1): for c in range(1, cols - 1): # Check for X-MAS pattern if (grid[r-1][c-1] == 'M' and grid[r][c-1] == 'A' and grid[r+1][c-1] == 'S' and grid[r-1][c+1] == 'M' and grid[r][c+1] == 'A' and grid[r+1][c+1] == 'S'): count += 1 if (grid[r-1][c+1] == 'M' and grid[r][c+1] == 'A' and grid[r+1][c+1] == 'S' and grid[r-1][c-1] == 'M' and grid[r][c-1] == 'A' and grid[r+1][c-1] == 'S'): count += 1 return count file = "input.txt" grid = read_input(file) # Part 1 result1 = count_xmas(grid) print(result1) # Part 2 result2 = count_x_mas(grid) print(result2)