-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.solution.py
100 lines (82 loc) · 2.91 KB
/
day10.solution.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# day 10
from collections import namedtuple
from sys import stderr
with open('day10.input.txt') as f:
mmaze = [line.strip() for line in f.readlines()]
Tile = namedtuple('Tile', ('x', 'y'))
def maze(t):
return mmaze[t.x][t.y]
for i, line in enumerate(mmaze):
if line.find('S') != -1:
start = Tile(i, line.find('S'))
def get_next(prev, tile):
step = {
('|', (-1, 0)): (1, 0),
('|', (1, 0)): (-1, 0),
('-', (0, 1)): (0, -1),
('-', (0, -1)): (0, 1),
('7', (0, -1)): (1, 0),
('7', (1, 0)): (0, -1),
('J', (-1, 0)): (0, -1),
('J', (0, -1)): (-1, 0),
('L', (-1, 0)): (0, 1),
('L', (0, 1)): (-1, 0),
('F', (1, 0)): (0, 1),
('F', (0, 1)): (1, 0),
}
if not (tile.x >= 0 and tile.x < len(mmaze) and tile.y >= 0
and tile.y < len(mmaze[tile.x])):
return None, None
key = (maze(tile), (prev.x - tile.x, prev.y - tile.y))
if key in step:
nxt = Tile(*(step[key]))
return tile, Tile(tile.x + nxt.x, tile.y + nxt.y)
return None, None
def travel(prev, tile):
path = [prev, tile]
while tile != start:
prev, tile = get_next(prev, tile)
if not prev:
return []
path.append(tile)
return path
for nx, ny in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nxt = Tile(start.x + nx, start.y + ny)
path = travel(start, nxt)
if path:
print(len(path) // 2)
break
# part 2
if Tile(start.x - 1, start.y) in path and Tile(start.x + 1, start.y) in path:
mmaze[start.x] = mmaze[start.x].replace('S', '|')
elif Tile(start.x, start.y - 1) in path and Tile(start.x, start.y + 1) in path:
mmaze[start.x] = mmaze[start.x].replace('S', '-')
elif Tile(start.x, start.y - 1) in path and Tile(start.x - 1, start.y) in path:
mmaze[start.x] = mmaze[start.x].replace('S', 'J')
elif Tile(start.x, start.y - 1) in path and Tile(start.x + 1, start.y) in path:
mmaze[start.x] = mmaze[start.x].replace('S', 'L')
elif Tile(start.x, start.y + 1) in path and Tile(start.x - 1, start.y) in path:
mmaze[start.x] = mmaze[start.x].replace('S', '7')
elif Tile(start.x, start.y + 1) in path and Tile(start.x + 1, start.y) in path:
mmaze[start.x] = mmaze[start.x].replace('S', 'F')
else:
print('error', file=stderr)
icount = 0
for i, row in enumerate(mmaze):
inside = False
boundary = set(p for p in path if p.x == i)
for j in range(len(row)):
t = Tile(i, j)
if t in boundary:
if maze(t) == '|':
inside = not inside
else:
st = maze(t)
while maze(Tile(i, j + 1)) == '-':
j += 1
end = maze(Tile(i, j + 1))
if (st, end) in set((('F', 'J'), ('L', '7'))):
inside = not inside
elif inside:
icount += 1
print(icount)