m = [ [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] ] def getm(file): matrix = [] for line in open(file, 'r'): matrix.append(list(map(lambda x: int(x), line.split(',')))) return matrix def calc_short(short, nl): for i in range(len(nl)): nl[i] += min(short[i], short[i + 1]) return nl def short_lu(matrix): short = [0] for x in range(len(matrix)): nl = [] for i in range(x + 1): nl.append(matrix[x - i][i]) short = calc_short(short[:1] + short + short[-1:], nl) return short def short_rd(matrix, short): for x in range(len(matrix), (len(matrix) - 1) * 2 + 1): nl = [] for i in range(x - len(matrix) + 1, len(matrix)): nl.append(matrix[x - i][i]) short = calc_short(short, nl) return short[0] m = getm('../resource/matrix.txt') print(short_rd(m, short_lu(m)))