NOTE: This problem is a more challenging version of Problem 81.
The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994.
Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing a 80 by 80 matrix, from the left column to the right column.
Similar to P81.
We can split matrix vertically into smaller matrix (one column right once a time).
from urllib.request import urlopen
with urlopen('https://projecteuler.net/project/resources/p082_matrix.txt') as f:
resp = f.read().decode('utf-8')
matrix = [list(map(int, line.split(','))) for line in resp.splitlines()]
len(matrix), len(matrix[0])
example_matrix = [
[131, 673, 234, 103, 18],
[201, 96, 342, 965, 150],
[630, 803, 746, 422, 111],
[537, 699, 497, 121, 956],
[805, 732, 524, 37, 331]
]
def get_col_inner_sum(col, start, end):
if start <= end:
return sum(col[start:end+1])
else:
return sum(col[end:start+1])
get_col_inner_sum([1, 2, 3, 4], 1, 3)
get_col_inner_sum([1, 2, 3, 4], 2, 0)
def solve(matrix):
matrix_size = (len(matrix), len(matrix[0]))
assert matrix_size[0] == matrix_size[1]
def get_matrix_col(col):
return [line[col] for line in matrix]
def get_min_right(start_col, right_most_col):
if start_col == right_most_col:
return get_matrix_col(start_col)
else:
col = get_matrix_col(start_col)
adjacent_min_col = get_min_right(start_col+1, right_most_col)
min_col = []
for i in range(len(col)):
min_i_candidates = []
for j in range(len(adjacent_min_col)):
s = get_col_inner_sum(col, i, j)
min_i_candidates.append(s + adjacent_min_col[j])
min_col.append(min(min_i_candidates))
return min_col
return min(get_min_right(0, matrix_size[1]-1))
solve(example_matrix)
solve(matrix)