算法---深度遍历、广度遍历

一、深度遍历

题目1:一张N*M的地图上每个点的海拔高度不同;从当前点只能访问上、下、左、右四个点中还没有到达的点,且下一步选择的点的海拔高度必须高于当前点,求从地图中的点A到点B总的路径条数除以10^9的余

思路:dfs

代码如下:

# row, col = map(int, input().split())
# graph = []
# for _ in range(row):
#     graph.append(list(map(int, input().split())))
# print(graph)

# x1, y1, x2, y2 = map(int, input().split())

dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]#上,下,右,左
M = 10 ** 9
res = [0]

graph = [[0, 1, 0, 0, 0], [0, 2, 3, 0, 0], [0, 0, 4, 5, 0], [0, 0, 7, 6, 0]]
row = 4
col = 5
x1, y1, x2, y2 = 0, 1, 3, 2

def dfs(x1, y1, visited):
    if x1 == x2 and y1 == y2:
        res[0] += 1
        return
    for i, j in dirs:#遍历4个方向,判断下一步哪步可行,然后从这步开始,继续深度遍历,直到到达终点
        tmp_x = i + x1
        tmp_y = j + y1
        if 0 <= tmp_x < row and 0 <= tmp_y < col and graph[tmp_x][tmp_y] > graph[x1][y1] \
                and (tmp_x, tmp_y) not in visited:
            dfs(tmp_x, tmp_y, visited | {(tmp_x, tmp_y)})
    print (visited)
dfs(x1, y1, {(x1, y1)})

print(res[0] % M)

  

 

转载于:https://www.cnblogs.com/nxf-rabbit75/p/10686503.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值