回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
我们用回溯法来写迷宫问题,如下:
maze = [[0, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 1, 1, 0, 1], [1, 0, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 1, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1]]stack = []dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]def mark(m, p): m[p[0]][p[1]] = 2def judge(m, p): return m[p[0]][p[1]] == 0def maze_solver(m, s, e): if s == e: print(s) return mark(m, s) stack.append(s) while len(stack): pos = stack[-1] stack.pop() for i in range(4): nextp = (pos[0] + dirs[i][0], pos[1] + dirs[i][1]) if nextp == e: print("路径:", stack) return if judge(m, nextp): stack.append(pos) mark(m, nextp) stack.append(nextp) break print("找不到路径")for i in range(8): for j in range(8): print(maze[i][j], end='') print()maze_solver(maze, s=(0, 0), e=(7, 7))
来源:https://www.cnblogs.com/whitehawk/p/10964846.html