-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.py
46 lines (32 loc) · 1.12 KB
/
part2.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
from heapq import heappush, heappop
def traverse(city):
width, height = len(city[0]), len(city)
seen = set()
queue = []
heappush(queue, (0, 0, 0, False))
heappush(queue, (0, 0, 0, True))
while queue:
cost, x, y, axis = heappop(queue)
if x == width - 1 and y == height - 1:
return cost
if (x, y, axis) in seen:
continue
seen.add((x, y, axis))
for direction in (-1, 1):
new_y, new_x = y, x
add_cost = 0
for distance in range(1, 11):
if axis:
new_x += direction
if not 0 <= new_x < width:
break
else:
new_y += direction
if not 0 <= new_y < height:
break
add_cost += city[new_y][new_x]
if distance >= 4:
heappush(queue, (cost + add_cost, new_x, new_y, not axis))
with open('input.txt') as file:
city = [list(map(int, line)) for line in filter(None, map(str.strip, file))]
print(traverse(city))