Advertisement
CrayonCrayoff

Advent of Code Day 16 Part 1

Dec 23rd, 2024
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. from collections import deque
  2.  
  3.  
  4. with open("day16input.txt") as f:
  5.     grid = f.read().splitlines()
  6.  
  7.  
  8. def race(maze: list[str]) -> int:
  9.     rows = len(maze)
  10.     cols = len(maze[0])
  11.  
  12.     # find start and end points
  13.     start = (-1, -1)
  14.     end = (-1, -1)
  15.     for row in range(rows):
  16.         for col in range(cols):
  17.             if maze[row][col] == 'S':
  18.                 # store start position and starting direction (east)
  19.                 start = (row, col, 0, 1)
  20.             elif maze[row][col] == 'E':
  21.                 end = (row, col)
  22.  
  23.     directions = [(0, -1), (-1, 0), (0, 1), (1, 0)]
  24.     queue = deque([start])
  25.     # keep track of the score for each node and the directions used to get to it
  26.     node_score = {start: 0}
  27.    
  28.     # recursive BFS, pop from start of list for current node, append all valid nodes at end of list
  29.     while queue:
  30.         y, x, dy, dx = queue.popleft()
  31.         curr_score = node_score[(y, x, dy, dx)]
  32.         # if we're at the finish, we can stop looking for new nodes
  33.         if maze[y][x] != 'E':
  34.             for dy2, dx2 in directions:
  35.                 # we don't want to go back to where we came from
  36.                 if (dy2, dx2) == (-dy, -dx):
  37.                     continue
  38.                 if maze[y+dy2][x+dx2] != '#':
  39.                     # if direction doesn't equal current node's direction, we turn
  40.                     if (dy2, dx2) != (dy, dx):
  41.                         new_score = curr_score + 1001
  42.                     else:
  43.                         new_score = curr_score + 1
  44.                     # update score and append to queue if we visit the node for the first time
  45.                     # also do this if our new score would be lower for that node and direction
  46.                     if ((y+dy2, x+dx2, dy2, dx2) not in node_score or
  47.                             ((y+dy2, x+dx2, dy2, dx2) in node_score and
  48.                              node_score[(y+dy2, x+dx2, dy2, dx2)] > new_score)):
  49.                         node_score[(y+dy2, x+dx2, dy2, dx2)] = new_score
  50.                         queue.append((y+dy2, x+dx2, dy2, dx2))
  51.  
  52.     return min([node_score[x] for x in node_score if (x[0], x[1]) == end])
  53.  
  54.  
  55. print(race(grid))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement