Advertisement
Guest User

Untitled

a guest
Dec 6th, 2024
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. f = open('input.txt')
  2. lines = [l.strip() for l in f.readlines()]
  3.  
  4. grid = []
  5. was = {}
  6. pos = (0, 0)
  7. dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)]
  8. for l in lines:
  9. if '^' in l:
  10. pos = (l.index('^'), len(grid))
  11. l = l.replace('^', '.')
  12. grid.append(l)
  13.  
  14. def plus(pos1, d):
  15. return (pos1[0] + d[0], pos1[1] + d[1])
  16.  
  17. def is_valid_pos(grid, pos):
  18. return 0 <= pos[0] < len(grid[0]) and 0 <= pos[1] < len(grid)
  19.  
  20. def can_go(grid, pos, d):
  21. npos = plus(pos, d)
  22. return is_valid_pos(grid, npos) and grid[npos[1]][npos[0]] != '#'
  23.  
  24. def will_cycle(gr, pos, d, sd, was):
  25. global dirs, directions
  26. p = pos
  27. nwas = {}
  28. starti = dirs.index(d)
  29. obs = plus(pos, sd)
  30. grid = gr.copy()
  31. grid[obs[1]] = grid[obs[1]][:obs[0]] + '#' + grid[obs[1]][obs[0] + 1:]
  32. while is_valid_pos(grid, p):
  33. for j in range(starti, len(dirs)):
  34. dir = dirs[j]
  35. while can_go(grid, p, dir):
  36. p = plus(p, dir)
  37. if (p in nwas.keys() and dir in nwas[p]) or(p in was.keys() and dir in was[p]):
  38. return obs
  39. if p not in nwas.keys():
  40. nwas[p] = []
  41. if dir not in nwas[p]:
  42. nwas[p].append(dir)
  43. if not is_valid_pos(grid, plus(p, dir)):
  44. p = plus(p, dir)
  45. break
  46. starti = 0
  47. return 0
  48.  
  49. steps = 0
  50. s = 0
  51. was[pos] = [dirs[0]]
  52. was_obs = []
  53. START = pos
  54. while is_valid_pos(grid, pos):
  55. for i in range(len(dirs)):
  56. d = dirs[i]
  57. while can_go(grid, pos, d):
  58. if can_go(grid, pos, d) and plus(pos, d) != START:
  59. nextd = dirs[(i + 1) % len(dirs)]
  60. will = will_cycle(grid, pos, nextd, d, dict(was))
  61. if will not in was_obs and will != 0:
  62. was_obs.append(will)
  63. pos = plus(pos, d)
  64. if pos not in was.keys():
  65. was[pos] = []
  66. was[pos].append(d)
  67.  
  68. if not is_valid_pos(grid, plus(pos, d)):
  69. pos = plus(pos, d)
  70. break
  71.  
  72. print(len(was_obs))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement