AdventOfCode/2024/18/solution.py

84 lines
2.2 KiB
Python
Raw Normal View History

2024-12-18 07:09:36 +01:00
#!/bin/python3
import sys,time,re
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int,get_re,nprint,lprint,loadFile,bfs,get_value_in_direction,addTuples,grid_valid
start_time = time.time()
input_f = 'input'
#########################################
# #
# Part 1 #
# #
#########################################
2024-12-19 18:04:23 +01:00
if input_f == 'test':
w = 6
h = 6
size = 12
else:
2024-12-18 07:09:36 +01:00
w = 70
h = 70
2024-12-19 18:04:23 +01:00
size = 1024
end = (h,w)
start = (0,0)
2024-12-18 07:09:36 +01:00
2024-12-19 18:04:23 +01:00
instructions = []
grid = []
with open(input_f) as file:
for line in file:
l = list2int(line.rstrip().split(','))
instructions.append((l[1],l[0]))
grid = [[ '.' for x in range(0,w+1)] for y in range(0,h+1)]
2024-12-18 07:09:36 +01:00
2024-12-19 18:04:23 +01:00
def is_goal(node):
return True if node == end else False
def get_neighbors(node):
directions = ['up','down','left','right']
offsets = {
'up': (-1, 0),
'down': (1, 0),
'left': (0, -1),
'right': (0, 1),
}
neighbors = []
for d in directions:
tmp = addTuples(offsets[d],node)
if get_value_in_direction(grid,node,d) != '#' and grid_valid(tmp[0],tmp[1],grid):
neighbors.append((tmp[0],tmp[1]))
return neighbors
def part1():
for i in range(size):
x = instructions[i]
grid[x[0]][x[1]] = '#'
2024-12-18 07:09:36 +01:00
goal_nodes, path = bfs((0,0),is_goal,get_neighbors)
2024-12-19 18:04:23 +01:00
return len(path[goal_nodes[0]])-1, path
goal_nodes, path = part1()
2024-12-18 07:09:36 +01:00
start_time = time.time()
2024-12-19 18:04:23 +01:00
print('Part 1:',goal_nodes, '\t\t', round((time.time() - start_time)*1000), 'ms')
2024-12-18 07:09:36 +01:00
#########################################
# #
# Part 2 #
# #
#########################################
def part2():
2024-12-19 18:04:23 +01:00
new_path = path
for i in range(size,len(instructions)):
x = instructions[i]
grid[x[0]][x[1]] = '#'
goal_nodes, new_path = bfs((0,0),is_goal,get_neighbors)
if not goal_nodes:
return x[1],x[0]
2024-12-18 07:09:36 +01:00
start_time = time.time()
print('Part 2:',part2(), '\t\t', round((time.time() - start_time)*1000), 'ms')