DFS回溯

给一个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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值