|
| 1 | +import collections |
| 2 | + |
| 3 | + |
| 4 | +def load_map(filename): |
| 5 | + with open(filename, "r") as f: |
| 6 | + map_data = f.read() |
| 7 | + |
| 8 | + return [list(row) for row in map_data.split()] |
| 9 | + |
| 10 | + |
| 11 | +def bfs(grid, start, end): |
| 12 | + height = len(grid) |
| 13 | + width = len(grid[0]) |
| 14 | + end_x, end_y = end |
| 15 | + queue = collections.deque([[start]]) |
| 16 | + visited = set([start]) |
| 17 | + |
| 18 | + while queue: |
| 19 | + path = queue.popleft() |
| 20 | + x, y = path[-1] |
| 21 | + if x == end_x and y == end_y: |
| 22 | + return path |
| 23 | + for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: |
| 24 | + nx, ny = x + dx, y + dy |
| 25 | + if ( |
| 26 | + 0 <= nx < height |
| 27 | + and 0 <= ny < width |
| 28 | + and grid[nx][ny] != "#" |
| 29 | + and (nx, ny) not in visited |
| 30 | + ): |
| 31 | + queue.append(path + [(nx, ny)]) |
| 32 | + visited.add((nx, ny)) |
| 33 | + return path |
| 34 | + |
| 35 | + |
| 36 | +def find_pos(grid, el): |
| 37 | + for row_ind, row in enumerate(grid): |
| 38 | + for col_ind, cell in enumerate(row): |
| 39 | + if cell == el: |
| 40 | + return (row_ind, col_ind) |
| 41 | + |
| 42 | + |
| 43 | +def is_within_bounds(point_x, point_y, max_row, max_col): |
| 44 | + return 0 <= point_x < max_row and 0 <= point_y < max_col |
| 45 | + |
| 46 | + |
| 47 | +def find_cheat_positions(racepath, field, max_row, max_col, threshold): |
| 48 | + start_ind = racepath.index(field) |
| 49 | + x, y = field |
| 50 | + |
| 51 | + pos = set() |
| 52 | + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] |
| 53 | + for dx1, dy1 in directions: |
| 54 | + nx1, ny1 = x + dx1, y + dy1 |
| 55 | + if is_within_bounds(nx1, ny1, max_row, max_col): |
| 56 | + for dx2, dy2 in directions: |
| 57 | + nx2, ny2 = nx1 + dx2, ny1 + dy2 |
| 58 | + # check if is back on normal track again |
| 59 | + if ( |
| 60 | + is_within_bounds(nx2, ny2, max_row, max_col) |
| 61 | + and (nx2, ny2) in racepath |
| 62 | + ): |
| 63 | + end_ind = racepath.index((nx2, ny2)) |
| 64 | + if start_ind - end_ind - 2 >= threshold: |
| 65 | + # we need to spend 2 picoseconds for the cheating |
| 66 | + pos.add(((x, y), (nx2, ny2))) |
| 67 | + return pos |
| 68 | + |
| 69 | + |
| 70 | +def cheat_threshold(racetrack, threshold): |
| 71 | + start = find_pos(racetrack, "S") |
| 72 | + end = find_pos(racetrack, "E") |
| 73 | + racepath = bfs( |
| 74 | + racetrack, start, end |
| 75 | + ) # there is only a single path from the start to the end |
| 76 | + max_row = len(racetrack) |
| 77 | + max_col = len(racetrack[0]) |
| 78 | + |
| 79 | + pos = set() |
| 80 | + for field in racepath: |
| 81 | + pos.update(find_cheat_positions(racepath, field, max_row, max_col, threshold)) |
| 82 | + |
| 83 | + return pos |
| 84 | + |
| 85 | + |
| 86 | +if "__main__" == __name__: |
| 87 | + racetrack = load_map("Day_20/puzzle_input.txt") |
| 88 | + pos = cheat_threshold(racetrack, 100) |
| 89 | + print(len(pos)) |
0 commit comments