将该矩阵M视为图,矩阵中每个元素$M_{ij}$都是图中的节点,它与其上下左右的相邻元素连通,用Dijkstra算法求最短路径即得结果$425185$。
a=[]
with open("083_matrix.txt") as f:
for line in f:
a.append([int(i) for i in line.split(",")])
res={(0,0):a[0][0]}
d={}
for i in range(80):
for j in range(80):
d[(i,j)]=-1
d[(0,1)]=a[0][0]+a[0][1]
d[(1,0)]=a[0][0]+a[1][0]
del d[(0,0)]
while d:
i,j=min([d[k],k] for k in d if d[k]>0)[1]
res[(i,j)]=d[(i,j)]
if i>0 and (i-1,j) in d and (d[(i-1,j)] < 0 or d[(i-1,j)]>res[(i,j)]+a[i-1][j]):
d[(i-1,j)]=res[(i,j)]+a[i-1][j]
if i < 79 and (i+1,j) in d and (d[(i+1,j)] < 0 or d[(i+1,j)]>res[(i,j)]+a[i+1][j]):
d[(i+1,j)]=res[(i,j)]+a[i+1][j]
if j>0 and (i,j-1) in d and (d[(i,j-1)] < 0 or d[(i,j-1)]>res[(i,j)]+a[i][j-1]):
d[(i,j-1)]=res[(i,j)]+a[i][j-1]
if j < 79 and (i,j+1) in d and (d[(i,j+1)] < 0 or d[(i,j+1)]>res[(i,j)]+a[i][j+1]):
d[(i,j+1)]=res[(i,j)]+a[i][j+1]
del d[(i,j)]
print res[(79,79)]
|