-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday4.py
65 lines (56 loc) · 1.87 KB
/
day4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def count_xmas(grid, word="XMAS"):
rows = len(grid)
cols = len(grid[0])
directions = [
(0, 1), # Right
(0, -1), # Left
(1, 0), # Down
(-1, 0), # Up
(1, 1), # Down-right diagonal
(-1, -1), # Up-left diagonal
(1, -1), # Down-left diagonal
(-1, 1) # Up-right diagonal
]
word_length = len(word)
count = 0
def is_valid(x, y):
return 0 <= x < rows and 0 <= y < cols
for x in range(rows):
for y in range(cols):
for dx, dy in directions:
match = True
for i in range(word_length):
nx, ny = x + i * dx, y + i * dy
if not is_valid(nx, ny) or grid[nx][ny] != word[i]:
match = False
break
if match:
count += 1
return count
def count_x_mas(grid):
rows = len(grid)
cols = len(grid[0])
patterns = ["MAS", "SAM"]
count = 0
def is_valid(x, y):
return 0 <= x < rows and 0 <= y < cols
for x in range(1, rows - 1):
for y in range(1, cols - 1):
if grid[x][y] == 'A':
for tl in patterns:
for br in patterns:
if (
is_valid(x - 1, y - 1) and is_valid(x + 1, y + 1) and
is_valid(x - 1, y + 1) and is_valid(x + 1, y - 1) and
grid[x - 1][y - 1] + grid[x][y] + grid[x + 1][y + 1] == tl and
grid[x - 1][y + 1] + grid[x][y] + grid[x + 1][y - 1] == br
):
count += 1
return count
grid = []
with open('input_day4.txt', 'r') as f:
lines = f.readlines()
for line in lines:
grid.append(line.strip())
print(count_xmas(grid))
print(count_x_mas(grid))