My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add 2021/15

+55
+55
2021/day15.py
··· 1 + import fileinput 2 + import heapq 3 + from utils import Point 4 + 5 + 6 + def shortest_path(graph, start, end): 7 + """Returns the shortest path from start to end in graph.""" 8 + horizon = [(0, start)] 9 + seen = set() 10 + 11 + while horizon: 12 + depth, node = heapq.heappop(horizon) 13 + 14 + if node == end: 15 + return depth 16 + elif node in seen: 17 + continue 18 + 19 + seen.add(node) 20 + 21 + for neigh in node.neighbours_4(): 22 + if neigh not in graph: 23 + continue 24 + 25 + heapq.heappush(horizon, (depth + graph[neigh], neigh)) 26 + 27 + return -1 28 + 29 + 30 + CAVE = {} 31 + 32 + # Read problem input and solve part 1. 33 + for y, line in enumerate(fileinput.input()): 34 + for x, c in enumerate(line.strip()): 35 + CAVE[Point(x, y)] = int(c) 36 + WIDTH = x + 1 37 + 38 + HEIGHT = y + 1 39 + 40 + print "Part 1:", shortest_path(CAVE, Point(0, 0), Point(x, y)) 41 + 42 + 43 + # Replicate CAVE tiles to solve part 2. 44 + for y in range(HEIGHT*5): 45 + for x in range(WIDTH*5): 46 + if Point(x, y) not in CAVE: 47 + dx = x // WIDTH 48 + dy = y // HEIGHT 49 + 50 + # Need to subtract one, take modulo, then add one because we 51 + # are dealing with the range 1-9, not 0-8. 52 + val = (CAVE[Point(x % WIDTH, y % HEIGHT)] + (dx + dy)) 53 + CAVE[Point(x, y)] = ((val - 1) % 9) + 1 54 + 55 + print "Part 2:", shortest_path(CAVE, Point(0, 0), Point(x, y))