python迷宫问题的所有路径_python——迷宫问题总结
關(guān)于迷宮問題,常見會問能不能到達(dá)某點(diǎn),以及打印到達(dá)的最短路徑。可以用回溯法+遞歸來解決
代碼一:dfs + 回溯
將矩陣外圍以及路障統(tǒng)一設(shè)置為-1
設(shè)置current_step和next_step兩個值。如果面臨的點(diǎn)大于next_step,或者從未走過,就可以對它遞歸
存儲矩陣:直接在原迷宮上修改,每個點(diǎn)標(biāo)記的是從起點(diǎn)過來經(jīng)過的步數(shù),遇到0或者是比當(dāng)前大至少2的,就考察
# -*- coding:utf-8 -*-
def init():
global graph
graph.append([-1, -1, -1, -1, -1, -1, -1])
graph.append([-1, 0, 0, -1, 0, 0, -1])
graph.append([-1, 0, -1, 0, 0, 0, -1])
graph.append([-1, 0, -1, 0, -1, -1, -1])
graph.append([-1, 0, -1, 0, 0, 0, -1])
graph.append([-1, 0, 0, 0, -1, 0, -1])
graph.append([-1, 0, 0, 0, 0, 0, -1])
graph.append([-1, -1, -1, -1, -1, -1, -1])
#深度優(yōu)先遍歷
def deepFirstSearch( steps , x, y ):
global graph
current_step = steps + 1
print(x, y, current_step )
graph[x][y] = current_step
next_step = current_step + 1
'''
遍歷周圍4個點(diǎn):
如果周圍節(jié)點(diǎn)不是-1 說明 不是障礙 在此基礎(chǔ)上:
里面是0 說明沒遍歷過 我們把它修改成當(dāng)前所在位置步數(shù)加1
里面比當(dāng)前的next_step大 說明不是最優(yōu)方案 就修改它
里面比當(dāng)前next_step說明當(dāng)前不是最優(yōu)方案,不修改
'''
if not(x-1== 1 and y==1) and graph[x-1][y] != -1 and ( graph[x-1][y]>next_step or graph[x-1][y] ==0 ) : #上
deepFirstSearch(current_step, x-1 , y )
if not(x == 1 and y-1==1) and graph[x][y-1] != -1 and ( graph[x][y-1]>next_step or graph[x][y-1] ==0 ) : #左
deepFirstSearch(current_step, x , y-1 )
if not(x == 1 and y+1==1) and graph[x][y+1] != -1 and ( graph[x][y+1]>next_step or graph[x][y+1]==0 ) : #右
deepFirstSearch(current_step, x , y+1 )
if not(x+1== 1 and y==1) and graph[x+1][y] != -1 and ( graph[x+1][y]>next_step or graph[x+1][y]==0 ) : #下
deepFirstSearch(current_step, x+1 , y )
if __name__ == "__main__":
graph = []
init()
deepFirstSearch(-1,1,1)
print(graph[1][5])
代碼二:也是回溯
這里0是可走,1是路障,用while來做循環(huán)。如果某點(diǎn)的附近有判斷可走的新點(diǎn),就將新點(diǎn)append進(jìn)stack,走過了標(biāo)記為-1;如果四個方向都沒有,就從舊點(diǎn)從stack中pop掉,標(biāo)上-1,進(jìn)行回溯。
存儲矩陣:stack中存儲的0是可走,1是路障,-1是走過的或者是死路
maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,1,0,0,1],
[1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1],
[1,0,1,1,1,0,1,1,0,1],
[1,1,0,0,0,0,0,1,0,1],
[1,1,1,1,1,1,1,1,1,1]
]
dirs = [lambda x, y: (x + 1, y),
lambda x, y: (x - 1, y),
lambda x, y: (x, y - 1),
lambda x, y: (x, y + 1)]
def mpath(x1, y1, x2, y2):
stack = []
stack.append((x1, y1))
while len(stack) > 0:
curNode = stack[-1]
if curNode[0] == x2 and curNode[1] == y2:
#到達(dá)終點(diǎn)
for p in stack:
print(p)
return True
for dir in dirs:
nextNode = dir(curNode[0], curNode[1])
if maze[nextNode[0]][nextNode[1]] == 0:
#找到了下一個
stack.append(nextNode)
maze[nextNode[0]][nextNode[1]] = -1 # 標(biāo)記為已經(jīng)走過,防止死循環(huán)
break
else:#四個方向都沒找到
maze[curNode[0]][curNode[1]] = -1 # 死路一條,下次別走了
stack.pop() #回溯
print("沒有路")
return False
mpath(1,1,8,8)
總結(jié)
以上是生活随笔為你收集整理的python迷宫问题的所有路径_python——迷宫问题总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每10股转增2股是什么意思
- 下一篇: web python 自动化是什么_Se