Ayman72

AoC-2024-20

Dec 20th, 2024
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import re
  2. from datetime import datetime
  3. from collections import defaultdict
  4.  
  5. st = datetime.now()
  6.  
  7. grid = [list(line.strip()) for line in open("input.txt")]
  8. # grid = [list(line.strip()) for line in open("test.txt")]
  9.  
  10. SX = len(grid[0])
  11. SY = len(grid)
  12. d = [(1, 0), (0, 1), (-1, 0), (0, -1)]
  13.  
  14. def get(x, y):
  15.     if x < 0 or x >= SX or y < 0 or y >= SY:
  16.         return " "
  17.     return grid[y][x]
  18.  
  19. for y, l in enumerate(grid):
  20.     for x, c in enumerate(l):
  21.         if c == "S":
  22.             start = (x, y)
  23.         if c == "E":
  24.             end = (x, y)
  25.  
  26. track = [start]
  27.  
  28. # find the track
  29. nx, ny = start
  30. while (nx, ny) != end:
  31.     # print(nx, ny)
  32.     for dx, dy in d:
  33.         if get(nx + dx, ny + dy) in ('.', 'E') and not (nx + dx, ny + dy) in track:
  34.             track.append((nx + dx, ny + dy))
  35.             nx += dx
  36.             ny += dy
  37.             break
  38.  
  39. # print(f'Track length is {len(track)}')
  40.  
  41. answer = 0
  42. SAVES = 100
  43.  
  44. for i in range(len(track)):
  45.     for j in range(i+SAVES, len(track), 1):
  46.         # xa, ya is always before xb, yb, and a jump between them will save
  47.         # us at least SAVES steps
  48.         xa, ya = track[i]
  49.         xb, yb = track[j]
  50.         d = abs(xa - xb) + abs(ya - yb)
  51.         # we would be saving j-i-d steps,
  52.         # so if our manhattan dist is at most 20, and we are saving (j-i-d) steps, then we have a valid path
  53.         if d <= 20 and ((j-i-d) >= 100):
  54.             answer += 1
  55.  
  56. print(answer)
  57. print(f'Execution time: {datetime.now()-st}')
Advertisement
Add Comment
Please, Sign In to add comment