a = [] ff = open('matrix.txt.', 'r') for i in ff.readlines(): tmp = i.split(',') for j in xrange(len(tmp)): tmp[j] = int(tmp[j]) a.append(tmp) ff.close() path = [[a[0][0], [a[0][0]]]] n = len(a) for k in xrange(1, n): pathtmp = [] tmp = [a[k][0] + path[0][0], path[0][1][:]] tmp[1].append(a[k][0]) pathtmp.append(tmp) for i in xrange(1, k): if path[i - 1][0] < path[i][0]: flag = i - 1 else: flag = i tmp = [path[flag][0] + a[k - i][i], path[flag][1][:]] tmp[1].append(a[k - i][i]) pathtmp.append(tmp) tmp = [a[0][k] + path[k - 1][0], path[k - 1][1][:]] tmp[1].append(a[0][k]) pathtmp.append(tmp) path = pathtmp for k in xrange(n, 2 * n - 1): pathtmp = [] for i in xrange(2 * n - 1 - k): if path[i][0] < path[i + 1][0]: flag = i else: flag = i + 1 tmp = [path[flag][0] + a[n - 1 - i][k + i + 1 - n], path[flag][1][:]] tmp[1].append(a[n - 1 - i][k + i + 1 - n]) pathtmp.append(tmp) path = pathtmp print path