Guest User

Advent of Code 15 Python

a guest
Dec 15th, 2021
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. import sys
  2.  
  3. inp = [[int(x) for x in line] for line in sys.stdin.read().splitlines()]
  4.  
  5.  
  6. def solve(start, target, inp, part=1):
  7.  
  8.     inp_grid = {}
  9.  
  10.     for y in range(len(inp)):
  11.         for x in range(len(inp[y])):
  12.             inp_grid[(x, y)] = inp[y][x]
  13.  
  14.     grid_width = len(inp[0])
  15.     grid_height = len(inp[0])
  16.  
  17.     distances = {(x, y): float("inf")
  18.                  for x in range(len(inp[0])) for y in range(len(inp))}
  19.  
  20.     distances[(0, 0)] = 0
  21.  
  22.     if part == 2:
  23.         inp_grid_copy = inp_grid.copy()
  24.  
  25.         for i in range(5):
  26.             for j in range(5):
  27.                 # No adjustments to existing tile.
  28.                 if i + j == 0:
  29.                     continue
  30.  
  31.                 shift_x = grid_width * i
  32.                 shift_y = grid_height * j
  33.  
  34.                 for (x, y), val in inp_grid_copy.items():
  35.                     new_x = x + shift_x
  36.                     new_y = y + shift_y
  37.  
  38.                     val += i+j
  39.  
  40.                     while val > 9:
  41.                         val -= 9
  42.  
  43.                     inp_grid[(new_x, new_y)] = val
  44.                     distances[(new_x, new_y)] = float("inf")
  45.  
  46.         grid_width *= 5
  47.         grid_height *= 5
  48.  
  49.     unvisited = {(x, y) for x, y in inp_grid.keys()}
  50.  
  51.     visited = set()
  52.  
  53.     current = start
  54.     adjacent = [(0, 1), (1, 0), (0, -1), (-1, 0)]
  55.  
  56.     while True:
  57.         for x, y in adjacent:
  58.             dx = current[0] + x
  59.             dy = current[1] + y
  60.  
  61.             if dx in range(grid_width) and dy in range(grid_height):
  62.                 distances[(dx, dy)] = min(distances[(dx, dy)],
  63.                                           distances[current] + inp_grid[(dx, dy)])
  64.  
  65.         unvisited -= {current}
  66.         visited |= {current}
  67.  
  68.         if target in visited:
  69.             return distances
  70.  
  71.         current = min([(node, distances[node])
  72.                        for node in unvisited], key=lambda x: x[1])[0]
  73.  
  74.  
  75. target = (len(inp)-1, len(inp)-1)
  76.  
  77. part_1 = solve((0, 0), target, inp)
  78. print("Part 1:", part_1[target])
  79.  
  80. target2 = (5*(len(inp))-1, 5*(len(inp))-1)
  81.  
  82. part_2 = solve((0, 0), target2, inp, part=2)
  83. print("Part 2:", part_2[target2])
Advertisement
Add Comment
Please, Sign In to add comment