84 lines
2.2 KiB
Python
84 lines
2.2 KiB
Python
#!/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 #
|
|
# #
|
|
#########################################
|
|
|
|
if input_f == 'test':
|
|
w = 6
|
|
h = 6
|
|
size = 12
|
|
else:
|
|
w = 70
|
|
h = 70
|
|
size = 1024
|
|
end = (h,w)
|
|
start = (0,0)
|
|
|
|
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)]
|
|
|
|
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]] = '#'
|
|
|
|
goal_nodes, path = bfs((0,0),is_goal,get_neighbors)
|
|
|
|
return len(path[goal_nodes[0]])-1, path
|
|
|
|
goal_nodes, path = part1()
|
|
start_time = time.time()
|
|
print('Part 1:',goal_nodes, '\t\t', round((time.time() - start_time)*1000), 'ms')
|
|
|
|
|
|
#########################################
|
|
# #
|
|
# Part 2 #
|
|
# #
|
|
#########################################
|
|
def part2():
|
|
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]
|
|
|
|
start_time = time.time()
|
|
print('Part 2:',part2(), '\t\t', round((time.time() - start_time)*1000), 'ms') |