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/20

+68
+68
2024/day20.py
··· 1 + import fileinput 2 + from collections import deque, Counter 3 + from itertools import permutations 4 + 5 + from utils import Point 6 + 7 + 8 + def bfs(board, start, end): 9 + horizon = deque([(start, 0)]) 10 + seen = {} 11 + while horizon: 12 + pos, dist = horizon.popleft() 13 + if pos in seen: 14 + continue 15 + 16 + seen[pos] = dist 17 + 18 + if pos == END: 19 + return seen 20 + 21 + for n in pos.neighbours(): 22 + if BOARD.get(n) == '#' or n not in BOARD: 23 + continue 24 + horizon.append((n, dist + 1)) 25 + 26 + 27 + def num_cheat_paths(distances, max_cheat_dist): 28 + cheat_saves = Counter() 29 + for start, end in permutations(distances, 2): 30 + if distances[end] < distances[start]: 31 + continue 32 + 33 + cheat_dist = abs(start.dist_manhattan(end)) 34 + 35 + if cheat_dist > max_cheat_dist: 36 + continue 37 + 38 + saved = distances[end] - distances[start] - cheat_dist 39 + cheat_saves[saved] += 1 40 + 41 + num_cheats = 0 42 + for cheat_dist, count in cheat_saves.items(): 43 + if cheat_dist >= 100: 44 + num_cheats += count 45 + 46 + return num_cheats 47 + 48 + 49 + # Read problem input. 50 + BOARD = {} 51 + for y, line in enumerate(fileinput.input()): 52 + for x, c in enumerate(line.strip()): 53 + p = Point(x, y) 54 + if c == '#': 55 + BOARD[p] = '#' 56 + else: 57 + BOARD[p] = '.' 58 + if c == 'S': 59 + START = p 60 + elif c == 'E': 61 + END = p 62 + 63 + 64 + # Solve problem. 65 + distances = bfs(BOARD, START, END) 66 + 67 + print("Part 1:", num_cheat_paths(distances, 2)) 68 + print("Part 2:", num_cheat_paths(distances, 20))