Path sum: two ways
Problem 81
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.
Find the minimal path sum from the top left to the bottom right by only moving right and down in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing an 80 by 80 matrix.
from tools import load_data_integers
cache = [0] * (80 * 80)
matrix = []
height = 80
def move(x, y):
if cache[x + y * height] != 0:
return cache[x + y * height]
cache[x + y * height] = matrix[x + y * height]
# bottom right, aka last
if x == 79 and y == 79:
pass
# last right, can only go down
elif x == 79:
cache[x + y * height] += move(x, y + 1)
# last gottom, can only go right
elif y == 79:
cache[x + y * height] += move(x + 1, y)
# min between down vs right
else:
cache[x + y * height] += min(move(x + 1, y), move(x, y + 1))
# sum of bottom right
return cache[x + y * height]
def run():
global matrix
matrix = matrix + load_data_integers(81, ',', ',')
return move(0, 0)