You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

50 lines
1.3 KiB

#!/usr/bin/env python3
import sys
def trailhead_score(tm, x, y):
height = tm[y][x]
end_positions = set([])
if height == 9: return set([(x,y)])
directions = [(0,1), (1,0), (0,-1), (-1,0)]
for d in directions:
nx, ny = x+d[0], y+d[1]
if nx < 0 or ny < 0: continue
try:
if tm[ny][nx] - height == 1:
end_positions = end_positions.union(trailhead_score(tm, nx, ny))
except IndexError: continue
return end_positions
def trailhead_ranking(tm, x, y):
height = tm[y][x]
score = 0
if height == 9: return 1
directions = [(0,1), (1,0), (0,-1), (-1,0)]
for d in directions:
nx, ny = x+d[0], y+d[1]
if nx < 0 or ny < 0: continue
try:
if tm[ny][nx] - height == 1:
score += trailhead_ranking(tm, nx, ny)
except IndexError: continue
return score
if __name__ == '__main__':
tm = [[int(l) for l in line.strip('\n')] for line in open(sys.argv[1])]
res1, res2 = 0, 0
for j, y in enumerate(tm):
for i, x in enumerate(y):
if x == 0:
res1 += len(trailhead_score(tm, i, j))
res2 += trailhead_ranking(tm, i, j)
# challenge 1
print(f"challenge 1:\n{res1}\n")
# challenge 2
print(f"challenge 2:\n{res2}")