61 lines
1.3 KiB
Python
61 lines
1.3 KiB
Python
""" day 6 part 1 """
|
|
|
|
import fileinput
|
|
|
|
room = [list(line.strip()) for line in fileinput.input()]
|
|
|
|
start_pos = None
|
|
|
|
for y,line in enumerate(room):
|
|
for x,cell in enumerate(line):
|
|
if cell in '^<>v':
|
|
start_pos=(x,y,cell)
|
|
|
|
dirs = {
|
|
'^': (0,-1,'>'),
|
|
'>': (1,0,'v'),
|
|
'v': (0,1,'<'),
|
|
'<': (-1,0,'^')
|
|
}
|
|
|
|
def will_loop(room):
|
|
visited = set()
|
|
guard_x, guard_y, guard_d = start_pos
|
|
|
|
while 0 <= guard_y < len(room) and 0 <= guard_x < len(room[guard_y]):
|
|
dx, dy, turn = dirs[guard_d]
|
|
|
|
# print(guard_x,guard_y,guard_d)
|
|
step_x = guard_x + dx
|
|
step_y = guard_y + dy
|
|
|
|
if 0 <= step_y < len(room) and 0 <= step_x < len(room[step_y]) and room[step_y][step_x] == '#':
|
|
guard_d = turn
|
|
else:
|
|
if (guard_x,guard_y,guard_d) in visited:
|
|
return True, visited
|
|
visited.add((guard_x,guard_y,guard_d))
|
|
guard_x,guard_y = step_x,step_y
|
|
|
|
return False, visited
|
|
|
|
_, path = will_loop(room)
|
|
|
|
loops = 0
|
|
|
|
candidates = {(x,y) for x,y,_ in path}
|
|
print(len(candidates), candidates)
|
|
|
|
|
|
for x,y in candidates:
|
|
if room[y][x] == '.':
|
|
room[y][x] = '#'
|
|
# print('\n'.join([''.join(line) for line in room]))
|
|
if will_loop(room)[0]:
|
|
print('loop',x,y)
|
|
loops += 1
|
|
room[y][x] = '.'
|
|
|
|
print(loops)
|
|
|