project-euler/081_path_sum.py

24 lines
726 B
Python

#!/usr/bin/env python3
def from_file(name):
m = []
with open(name, 'r') as f:
for row in f.readlines():
m.append([int(num) if num[-1] != '\n' else int(num[:-1]) for num in row.split(',')])
return m
def main():
mx = from_file('data/081_matrix.txt')
rl = len(mx[0])
cl = len(mx)
for i in range(rl - 2, -1, -1): mx[cl - 1][i] += mx[cl - 1][i + 1]
for i in range(cl - 2, -1, -1): mx[i][rl - 1] += mx[i + 1][rl - 1]
for col in range(cl - 2, -1, -1):
for row in range(rl - 2, -1, -1):
mx[col][row] += mx[col][row + 1] if mx[col][row + 1] < mx[col + 1][row] else mx[col + 1][row]
return mx[0][0]
if __name__ == '__main__':
print(main())