Advertisement
kupuguy

Advent of Code 2024 Day 18

Dec 18th, 2024
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | Source Code | 0 0
  1. from pathlib import Path
  2. from collections import deque
  3.  
  4.  
  5. def parse(inp: str) -> list[complex]:
  6.     return [
  7.         complex(int(c[0]), int(c[1]))
  8.         for row in inp.splitlines()
  9.         if (c := row.split(","))
  10.     ]
  11.  
  12.  
  13. def part1(points: list[complex], number: int, width: int) -> int:
  14.     corrupted = set(points[:number])
  15.     good = set(
  16.         complex(x, y)
  17.         for y in range(width)
  18.         for x in range(width)
  19.         if complex(x, y) not in corrupted
  20.     )
  21.     start = 0 + 0j
  22.     end = complex(width - 1, width - 1)
  23.     points: deque[tuple[complex, int]] = deque([(start, 0)])
  24.     path: dict[complex, int] = {}
  25.     while points:
  26.         p, cost = points.popleft()
  27.         if p in path and cost <= path[p]:
  28.             continue
  29.         path[p] = cost
  30.         points.extend(
  31.             (q, cost + 1)
  32.             for q in (p + 1, p - 1, p + 1j, p - 1j)
  33.             if q in good and q not in path
  34.         )
  35.     return path[end] if end in path else None
  36.  
  37.  
  38. TEST = parse(Path("input/day18-test.txt").read_text())
  39. assert part1(TEST, 12, 7) == 22
  40.  
  41. INPUT = parse(Path("input/day18.txt").read_text())
  42. part1_total = part1(INPUT, 1024, 71)
  43. print(f"{part1_total=:,}")
  44.  
  45.  
  46. def part2(points: list[complex], number: int, width: int) -> str:
  47.     lo, hi = number, len(points)
  48.     while lo < hi:
  49.         n = (lo + hi) // 2 + 1
  50.         distance = part1(points, n, width)
  51.         if distance is None:
  52.             hi = n - 1
  53.         else:
  54.             lo = n
  55.     p = points[lo]
  56.     return f"{int(p.real)},{int(p.imag)}"
  57.  
  58.  
  59. assert part2(TEST, 12, 7) == "6,1"
  60. print("part2:", part2(INPUT, 1024, 71))  # 24,30
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement