Advertisement
hhoppe

Advent of code 2024 day 18 faster

Dec 17th, 2024 (edited)
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. def day18(s, *, size=71, n_step=1024, part2=False):  # Recompute only if shortest path is broken.
  2.   blocks = np.array([row.split(',') for row in s.splitlines()], int)[:, ::-1] + 1
  3.   grid = np.pad(np.full((size, size), '.'), 1, constant_values='#')
  4.   grid[tuple(blocks[:n_step].T)] = '#'
  5.  
  6.   def get_shortest_path() -> list[tuple[int, int]]:
  7.     yx, yxl = (1, 1), (size, size)
  8.     parent = {yx: (-1, -1)}
  9.     lst = [yx]
  10.     while lst:
  11.       lst2 = []
  12.       for yx in lst:
  13.         if yx == yxl:
  14.           path = []
  15.           while yx[0] >= 0:
  16.             path.append(yx)
  17.             yx = parent[yx]
  18.           return path
  19.         y, x = yx
  20.         for dy, dx in ((0, -1), (0, 1), (-1, 0), (1, 0)):
  21.           yx2 = y + dy, x + dx
  22.           if grid[yx2] == '.' and yx2 not in parent:
  23.             parent[yx2] = yx
  24.             lst2.append(yx2)
  25.       lst = lst2
  26.     return []
  27.  
  28.   if not part2:
  29.     return len(get_shortest_path()) - 1
  30.  
  31.   shortest_path = set(get_shortest_path())
  32.   for y, x in blocks[n_step:]:
  33.     grid[y, x] = '#'
  34.     if (y, x) in shortest_path:
  35.       shortest_path = set(get_shortest_path())
  36.       if not shortest_path:
  37.         return f'{x - 1},{y - 1}'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement