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 solution for 2024/16

+55
+55
2024/day16.py
··· 1 + import heapq 2 + import fileinput 3 + from collections import defaultdict 4 + 5 + from utils import Point, DIRS, E 6 + 7 + 8 + # Read problem input. 9 + BOARD = {} 10 + for y, line in enumerate(fileinput.input()): 11 + for x, c in enumerate(line.strip()): 12 + p = Point(x, y) 13 + BOARD[p] = '#' if c == '#' else '.' 14 + if c == 'S': 15 + START = p 16 + elif c == 'E': 17 + END = p 18 + 19 + 20 + # Best-first search around the maze. 21 + horizon = [(0, START, E, [])] 22 + seen = {} 23 + 24 + best_score = 1e9 25 + best_paths = defaultdict(list) 26 + 27 + while horizon: 28 + score, pos, d, path = heapq.heappop(horizon) 29 + 30 + if seen.get((pos, d), 1e9) < score: 31 + continue 32 + 33 + if pos == END: 34 + best_score = min(best_score, score) 35 + best_paths[score].append(path + [pos]) 36 + 37 + seen[pos, d] = score 38 + 39 + for dd in DIRS: 40 + np = pos + dd 41 + if dd == -d: 42 + continue 43 + 44 + if dd == d and BOARD.get(np) == '.': 45 + heapq.heappush(horizon, (score + 1, np, dd, [pos] + path)) 46 + elif BOARD.get(np) == '.': 47 + heapq.heappush(horizon, (score + 1001, np, dd, [pos] + path)) 48 + 49 + nice_tiles = set() 50 + for path in best_paths[best_score]: 51 + nice_tiles |= set(path) 52 + 53 + print("Part 1:", best_score) 54 + print("Part 2:", len(nice_tiles)) 55 +