Optimized 2024/06 P2
This commit is contained in:
parent
99bb81be32
commit
21f5c91742
@ -77,20 +77,32 @@ if part == 2:
|
|||||||
|
|
||||||
def isLoop(grid,pos,direction):
|
def isLoop(grid,pos,direction):
|
||||||
positions = []
|
positions = []
|
||||||
|
count = 0
|
||||||
while grid_valid(pos[0],pos[1],grid):
|
l = len(grid)
|
||||||
#nprint(grid,pos,'X')
|
|
||||||
if get_value_in_direction(grid,pos,direction) != '#':
|
|
||||||
cur = (pos[0],pos[1],direction)
|
|
||||||
|
|
||||||
if cur not in positions:
|
while grid_valid(pos[0],pos[1],grid):
|
||||||
positions.append(cur)
|
next = get_value_in_direction(grid,pos,direction)
|
||||||
else:
|
if next == '#':
|
||||||
return 1
|
|
||||||
pos = (pos[0]+offsets[direction][0],pos[1]+offsets[direction][1])
|
|
||||||
elif get_value_in_direction(grid,pos,direction) == '#':
|
|
||||||
direction = next_direction[direction]
|
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
|
return 0
|
||||||
|
|
||||||
grid = toGrid(input_f)
|
grid = toGrid(input_f)
|
||||||
@ -105,7 +117,6 @@ if part == 2:
|
|||||||
|
|
||||||
pos = start
|
pos = start
|
||||||
while grid_valid(pos[0],pos[1],grid):
|
while grid_valid(pos[0],pos[1],grid):
|
||||||
|
|
||||||
dir = get_value_in_direction(grid, pos)
|
dir = get_value_in_direction(grid, pos)
|
||||||
if get_value_in_direction(grid,pos,direction) != '#':
|
if get_value_in_direction(grid,pos,direction) != '#':
|
||||||
if pos not in steps:
|
if pos not in steps:
|
||||||
@ -115,11 +126,10 @@ if part == 2:
|
|||||||
direction = next_direction[direction]
|
direction = next_direction[direction]
|
||||||
steps.remove(start)
|
steps.remove(start)
|
||||||
print(len(steps))
|
print(len(steps))
|
||||||
|
|
||||||
result = 0
|
result = 0
|
||||||
for idx,i in enumerate(steps):
|
for idx,i in enumerate(steps):
|
||||||
print(idx)
|
grid[i[0]][i[1]] = '#'
|
||||||
new_grid = grid[:]
|
result += isLoop(grid,start,'up')
|
||||||
new_grid[i[0]][i[1]] = '#'
|
grid[i[0]][i[1]] = '.'
|
||||||
result += isLoop(new_grid,start,'up')
|
|
||||||
new_grid[i[0]][i[1]] = '.'
|
|
||||||
print(result)
|
print(result)
|
Loading…
Reference in New Issue
Block a user