回溯法-迷宫问题

回溯法(探索与回溯法)是一种选优搜索法,又称为试探法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

我们用回溯法来写迷宫问题,如下:

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]] = 2
def judge(m, p):
return m[p[0]][p[1]] == 0
def 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值