2024-12-10 00:02:45 -06:00

67 lines
2.4 KiB
Python

import time
start_time = time.time()
with open('puzzle.txt', 'r') as f:
lines = f.read().splitlines()
trailhead_map = {}
total_trailhead_score = 0
class endpoint:
def __init__(self, y, x):
self.y = y
self.x = x
def __hash__(self):
return (self.y, self.x).__hash__()
def __eq__(self, other):
return self.y == other.y and self.x == other.x
def next_step(depth, trailhead_map, line, column, reachable_ends, trailhead_rating):
if depth == 9:
reachable_ends.add(endpoint(line, column))
trailhead_rating += 1
return reachable_ends, trailhead_rating
if line + 1 in trailhead_map and trailhead_map[line + 1][column]['value'] == depth + 1:
reachable_ends, trailhead_rating = next_step(depth + 1, trailhead_map, line + 1, column, reachable_ends, trailhead_rating)
if column + 1 in trailhead_map[line] and trailhead_map[line][column + 1]['value'] == depth + 1:
reachable_ends, trailhead_rating = next_step(depth + 1, trailhead_map, line, column + 1, reachable_ends, trailhead_rating)
if line - 1 in trailhead_map and trailhead_map[line - 1][column]['value'] == depth + 1:
reachable_ends, trailhead_rating = next_step(depth + 1, trailhead_map, line - 1, column, reachable_ends, trailhead_rating)
if column - 1 in trailhead_map[line] and trailhead_map[line][column - 1]['value'] == depth + 1:
reachable_ends, trailhead_rating = next_step(depth + 1, trailhead_map, line, column - 1, reachable_ends, trailhead_rating)
return reachable_ends, trailhead_rating
for line_index, line in enumerate(lines):
for column_index, column in enumerate(list(line)):
if line_index not in trailhead_map:
trailhead_map[line_index] = {}
if column_index not in trailhead_map[line_index]:
trailhead_map[line_index][column_index] = {
'value': int(line[column_index])
}
trailhead_rating = 0
for line in trailhead_map:
for column in trailhead_map[line]:
if trailhead_map[line][column]['value'] == 0:
reachable_ends = set()
reachable_ends, trailhead_rating = next_step(0, trailhead_map, line, column, reachable_ends, trailhead_rating)
total_trailhead_score += len(reachable_ends)
print(total_trailhead_score)
print(trailhead_rating)
print(f'Total time: {time.time() - start_time}')