Optimized 2024/06 P2

This commit is contained in:
FrederikBaerentsen 2024-12-06 22:56:55 +01:00
parent 99bb81be32
commit 21f5c91742

View File

@ -77,20 +77,32 @@ if part == 2:
def isLoop(grid,pos,direction):
positions = []
count = 0
l = len(grid)
while grid_valid(pos[0],pos[1],grid):
#nprint(grid,pos,'X')
if get_value_in_direction(grid,pos,direction) != '#':
cur = (pos[0],pos[1],direction)
if cur not in positions:
positions.append(cur)
else:
return 1
pos = (pos[0]+offsets[direction][0],pos[1]+offsets[direction][1])
elif get_value_in_direction(grid,pos,direction) == '#':
next = get_value_in_direction(grid,pos,direction)
if next == '#':
direction = next_direction[direction]
#input()
else:
cur = (pos[0],pos[1],direction)
count += 1
# Instead of loging all visited positions and their direction,
# we can break out if we have visited more places than 4x the
# grid size (4 being once for each direction).
# This actually gives us the right result
#if cur not in positions:
# positions.append(cur)
#elif cur in positions:
# return 1
if count > 4*l*l:
return 1
pos = (pos[0]+offsets[direction][0],pos[1]+offsets[direction][1])
return 0
grid = toGrid(input_f)
@ -105,7 +117,6 @@ if part == 2:
pos = start
while grid_valid(pos[0],pos[1],grid):
dir = get_value_in_direction(grid, pos)
if get_value_in_direction(grid,pos,direction) != '#':
if pos not in steps:
@ -115,11 +126,10 @@ if part == 2:
direction = next_direction[direction]
steps.remove(start)
print(len(steps))
result = 0
for idx,i in enumerate(steps):
print(idx)
new_grid = grid[:]
new_grid[i[0]][i[1]] = '#'
result += isLoop(new_grid,start,'up')
new_grid[i[0]][i[1]] = '.'
grid[i[0]][i[1]] = '#'
result += isLoop(grid,start,'up')
grid[i[0]][i[1]] = '.'
print(result)