一、深度遍历
题目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)