Advertisement
hhoppe

Advent of code 2024 day 18 brute-force

Dec 17th, 2024 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. def day18(s, *, size=71, n_step=1024, part2=False):  # Brute-force.
  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_distance() -> int | None:
  7.     yx, yxl = (1, 1), (size, size)
  8.     visited = {yx}
  9.     lst = [yx]
  10.     for distance in itertools.count():
  11.       lst2 = []
  12.       for yx in lst:
  13.         if yx == yxl:
  14.           return distance
  15.         y, x = yx
  16.         for dy, dx in ((0, -1), (0, 1), (-1, 0), (1, 0)):
  17.           yx2 = y + dy, x + dx
  18.           if grid[yx2] == '.' and yx2 not in visited:
  19.             visited.add(yx2)
  20.             lst2.append(yx2)
  21.       lst = lst2
  22.       if not lst:
  23.         return None
  24.  
  25.   if not part2:
  26.     return get_distance()
  27.  
  28.   for y, x in blocks[n_step:]:
  29.     grid[y, x] = '#'
  30.     if get_distance() is None:
  31.       return f'{x - 1},{y - 1}'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement