与第81题类似,若$b(i,j)$是到第i行第j列为止的最小路径和,则
$$b(i,j)=min_kb(i-1,k)+d(i-1,k,i,j),$$
其中$d(i-1,k,i,j)$是从$(i-1,k)$先向右一格再向上或向下到达$(i,j)$的路径(若先向上则显然直接从$(i-1,k-1)$出发路径和更小所以第一步只考虑向右),结果是$260324$。
a=[]
with open("082_matrix.txt") as f:
for line in f:
a.append([int(i) for i in line.split(",")])
b=[[a[i][j] if j==0 else -1 for j in range(80)] for i in range(80)]
for j in range(1,80):
for i in range(80):
b[i][j]=min(b[k][j-1]+(sum(a[x][j] for x in range(i,k+1)) if k>i else sum(a[x][j] for x in range(k,i+1))) for k in range(80))
print min(b[i][-1] for i in range(80))
|