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.

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

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.


In [5]:
import numpy as np

In [6]:
def foo(m):
    # s = [[2 ** 64 - 1] * len(m[0])] * len(m)  # Slow. 
    s = [[999999] * len(m[0])] * len(m)
    # s = [[2 ** 31 - 1] * len(m[0])] * len(m)  # Not slow.
    s = np.array(s)

    for column in range(len(m[0]) - 1):
        for row in range(len(m)):
            if column == 0:
                s[row, column] = m[row, column]
            else:
                for dir in (-1, 1):
                    r = range(row, 0 if dir < 0 else len(m)-1, dir)
                    # print 'd', row, column, dir, r
                    for r1 in r:
                        r2 = r1 + dir
                        if s[r1, column] + m[r2, column] >= s[r2, column]:
                            break
                        s[r2, column] = s[r1, column] + m[r2, column]
        for row in range(len(m)):
            s[row, column+1] = s[row, column] + m[row, column+1]

            # print s
    return min(s[...,-1])

In [7]:
n = [[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]]
n = np.array(n)
print n

%timeit foo(n)
foo(n)


[[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]]
1000 loops, best of 3: 201 us per loop
Out[7]:
994

In [8]:
# http://projecteuler.net/project/matrix.txt
n = np.array([map(int, line.strip().split(',')) for line in open('matrix.txt').readlines()])
# print n

%timeit foo(n)
foo(n)


10 loops, best of 3: 68.9 ms per loop
Out[8]:
260324