Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def day18(s, *, size=71, n_step=1024, part2=False): # Recompute only if shortest path is broken.
- blocks = np.array([row.split(',') for row in s.splitlines()], int)[:, ::-1] + 1
- grid = np.pad(np.full((size, size), '.'), 1, constant_values='#')
- grid[tuple(blocks[:n_step].T)] = '#'
- def get_shortest_path() -> list[tuple[int, int]]:
- yx, yxl = (1, 1), (size, size)
- parent = {yx: (-1, -1)}
- lst = [yx]
- while lst:
- lst2 = []
- for yx in lst:
- if yx == yxl:
- path = []
- while yx[0] >= 0:
- path.append(yx)
- yx = parent[yx]
- return path
- y, x = yx
- for dy, dx in ((0, -1), (0, 1), (-1, 0), (1, 0)):
- yx2 = y + dy, x + dx
- if grid[yx2] == '.' and yx2 not in parent:
- parent[yx2] = yx
- lst2.append(yx2)
- lst = lst2
- return []
- if not part2:
- return len(get_shortest_path()) - 1
- shortest_path = set(get_shortest_path())
- for y, x in blocks[n_step:]:
- grid[y, x] = '#'
- if (y, x) in shortest_path:
- shortest_path = set(get_shortest_path())
- if not shortest_path:
- return f'{x - 1},{y - 1}'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement