Path sum: three ways

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.

$$ \begin{pmatrix} 131 & 673 & \color{red}{234} & \color{red}{103} & \color{red}{18}\\ \color{red}{201} & \color{red}{96} & \color{red}{342} & 965 & 150\\ 630 & 803 & 746 & 422 & 111\\ 537 & 699 & 497 & 121 & 956\\ 805 & 732 & 524 & 37 & 331 \end{pmatrix} $$

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.


Idea

Similar to P81.

We can split matrix vertically into smaller matrix (one column right once a time).


In [1]:
from urllib.request import urlopen
In [2]:
with urlopen('https://projecteuler.net/project/resources/p082_matrix.txt') as f:
    resp = f.read().decode('utf-8')
In [3]:
matrix = [list(map(int, line.split(','))) for line in resp.splitlines()]
In [4]:
len(matrix), len(matrix[0])
Out[4]:
(80, 80)
In [5]:
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]
]
In [6]:
def get_col_inner_sum(col, start, end):
    if start <= end:
        return sum(col[start:end+1])
    else:
        return sum(col[end:start+1])
In [7]:
get_col_inner_sum([1, 2, 3, 4], 1, 3)
Out[7]:
9
In [8]:
get_col_inner_sum([1, 2, 3, 4], 2, 0)
Out[8]:
6
In [9]:
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))
In [10]:
solve(example_matrix)
Out[10]:
994
In [11]:
solve(matrix)
Out[11]:
260324