Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- f = open('input.txt')
- lines = [l.strip() for l in f.readlines()]
- grid = []
- was = {}
- pos = (0, 0)
- dirs = [(0, -1), (1, 0), (0, 1), (-1, 0)]
- for l in lines:
- if '^' in l:
- pos = (l.index('^'), len(grid))
- l = l.replace('^', '.')
- grid.append(l)
- def plus(pos1, d):
- return (pos1[0] + d[0], pos1[1] + d[1])
- def is_valid_pos(grid, pos):
- return 0 <= pos[0] < len(grid[0]) and 0 <= pos[1] < len(grid)
- def can_go(grid, pos, d):
- npos = plus(pos, d)
- return is_valid_pos(grid, npos) and grid[npos[1]][npos[0]] != '#'
- def will_cycle(gr, pos, d, sd, was):
- global dirs, directions
- p = pos
- nwas = {}
- starti = dirs.index(d)
- obs = plus(pos, sd)
- grid = gr.copy()
- grid[obs[1]] = grid[obs[1]][:obs[0]] + '#' + grid[obs[1]][obs[0] + 1:]
- while is_valid_pos(grid, p):
- for j in range(starti, len(dirs)):
- dir = dirs[j]
- while can_go(grid, p, dir):
- p = plus(p, dir)
- if (p in nwas.keys() and dir in nwas[p]) or(p in was.keys() and dir in was[p]):
- return obs
- if p not in nwas.keys():
- nwas[p] = []
- if dir not in nwas[p]:
- nwas[p].append(dir)
- if not is_valid_pos(grid, plus(p, dir)):
- p = plus(p, dir)
- break
- starti = 0
- return 0
- steps = 0
- s = 0
- was[pos] = [dirs[0]]
- was_obs = []
- START = pos
- while is_valid_pos(grid, pos):
- for i in range(len(dirs)):
- d = dirs[i]
- while can_go(grid, pos, d):
- if can_go(grid, pos, d) and plus(pos, d) != START:
- nextd = dirs[(i + 1) % len(dirs)]
- will = will_cycle(grid, pos, nextd, d, dict(was))
- if will not in was_obs and will != 0:
- was_obs.append(will)
- pos = plus(pos, d)
- if pos not in was.keys():
- was[pos] = []
- was[pos].append(d)
- if not is_valid_pos(grid, plus(pos, d)):
- pos = plus(pos, d)
- break
- print(len(was_obs))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement