mardi 28 juin 2011

Euler #81

#!/usr/bin/env python

def read_matrix(filename):
    res = []
    f = open(filename, 'r')
    for line in f.readlines():
        res.append(map(lambda x: int(x), line.strip().split(',')))
    return res

matrix = read_matrix('matrix.txt')
matrix_len = len(matrix)

for i in xrange(matrix_len):
    for j in xrange(matrix_len):
        if i > 0 and j > 0:
            s1 = matrix[i][j] + matrix[i - 1][j]
            s2 = matrix[i][j] + matrix[i][j - 1]
            matrix[i][j] = min(s1, s2)
        elif i == 0 and j > 0:
            matrix[i][j] = matrix[i][j - 1] + matrix[i][j]
        elif i > 0 and j == 0:
            matrix[i][j] = matrix[i - 1][j] + matrix[i][j]

print matrix[matrix_len - 1][matrix_len - 1]

Aucun commentaire:

Publier un commentaire