给一个5*5的矩阵,矩阵中的值含义如下:
# 0:可走点,但收益为0 # 正整数:取得该值的收益 # -1:障碍物,不可走 # -3:目标点
现在从起点(0,0)走到目标点-3(矩阵中只有一个目标点),求最短路径下收益的最大值?
例:给定矩阵,输出最大收益值
0, 2, 0, 2, 0
2, -1, 3, -1, 1
0, 2, 2, 2, 0
-1, 1, -1, 1, 1
0, 3, 0, 2, -3
思路:
用dfs回溯,遍历可以走的路径,再求出最短路径下,收益的最大值
代码:
import math
def DFS():
m, n = 5, 5
bb = [[0, 2, 0, 2, 0], [2, -1, 3, -1, 1], [0, 2, 2, 2, 0], [-1, 1, -1, 1, 1], [0, 3, 0, 2, -3]]
pathlist = []#保存路径点
total = 0#当前的收益值
outmax = 0#保存最大的收益值
outlen = math.inf#路径点列表的长度
def isarray(x, y):#判断当前点是否在矩阵内
return 0 <= x < m and 0 <= y < n
def arrayfun(array, x, y):
nonlocal total
nonlocal pathlist
nonlocal outmax
nonlocal outlen
if isarray(x, y) == 0:
return 0
if array[x][y] in [-1, -2]:#走过的点或者不可走的点
return 0
if array[x][y] == -3:#目标点
pathlist.append([x, y])#在列表中添加点
# print(total, outlist)#打印收益和所走路径
# print(bb)#打印当前矩阵状态
if len(pathlist) < outlen:#判断路径长度的最小值
outlen = len(pathlist)
outmax = total
elif len(pathlist) == outlen:#如果路径长度相等,取最大收益值
outmax = max(outmax, total)
pathlist.pop()#在列表中删除点,回溯
return 0
flag = array[x][y]
total += flag
array[x][y] = -2
pathlist.append([x, y])
arrayfun(array, x - 1, y)
arrayfun(array, x + 1, y)
arrayfun(array, x, y - 1)
arrayfun(array, x, y + 1)
array[x][y] = flag#回溯元素值
total -= flag#总收益回溯
pathlist.pop()#路径列表回溯
return 0
arrayfun(bb, 0, 0)
print(outmax)
print(outlen)
DFS()