In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.

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 [1]:
import numpy as np

In [2]:
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]
                if row > 0:
                    s[row, column] += s[row - 1, column]
            else:
                for dir in (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]
    return s[-1, -1]

In [3]:
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]]
10000 loops, best of 3: 178 us per loop
Out[3]:
2427

In [4]:
# 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: 49.1 ms per loop
Out[4]:
427337