问题:求矩阵左上至右下坐标的路径,使其路径上的值的和最大,并给出路径
解题思路:
利用动态规划,每一个当前坐标的最大和都是其左或上的坐标最大和与当前坐标值之和,从右下至左上逐步计算。
方法一:采用while循环,在循环的同时将路径上的值加入列表sum_list中(因为是从右下至左上计算,列表中的路径是倒过来的,用reverse函数正过来)
a = [5,5]
# b = [[1,1,1,1,2],
# [2,3,4,1,4],
# [3,1,4,2,4],
# [2,1,5,7,2],
# [4,3,3,4,5]]
b = [[3,5,1,3,4],
[1,5,4,3,2],
[3,5,2,5,7],
[4,3,1,3,5],
[1,4,3,2,2]]
sum_list = [b[-1][-1]]
i = a[0]-1
j = a[1]-1
while True:
if i == j == 0:
break
elif i == 0:
b[i][j] += b[i][j - 1]
sum_list.append(b[i][j-1])
j = j-1
elif j == 0:
b[i][j] += b[i - 1][j]
sum_list.append(b[i-1][j])
i = i-1
else:
if b[i - 1][j]>b[i][j - 1]:
b[i][j] += b[i - 1][j]
sum_list.append(b[i - 1][j])
i = i-1
else:
b[i][j] += b[i][j - 1]
sum_list.append(b[i][j - 1])
j = j-1
sum_list.reverse()
print(sum_list)
print(sum(sum_list))
结果:
[3, 5, 5, 4, 3, 5, 7, 5, 2]
39
方法二:双层for循环直接计算所有路径最大值和,没有给出路径
a = [5,5]
# b = [[1,1,1,1,2],
# [2,3,4,1,4],
# [3,1,4,2,4],
# [2,1,5,7,2],
# [4,3,3,4,5]]
b = [[3,5,1,3,4],
[1,5,4,3,2],
[3,5,2,5,7],
[4,3,1,3,5],
[1,4,3,2,2]]
sum_list = []
for i in range(a[0]):
for j in range(a[1]):
if i == j == 0:
continue
elif i == 0:
b[i][j] += b[i][j-1]
elif j == 0:
b[i][j] += b[i-1][j]
else:
b[i][j] += max(b[i-1][j],b[i][j-1])
max_value = b[-1][-1]
print(max_value)
结果:
39