gpt4 book ai didi

python - 试图解决迷宫(波前算法)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:51:17 25 4
gpt4 key购买 nike

您好,我正在尝试使用波形算法 (explained here) 在 Python 中编写迷宫求解程序。我正在使用嵌套循环遍历矩阵并更改数字,如 in this animated gif.

但是,它似乎只循环遍历矩阵的第一行,而没有继续执行其余行。我已经关注这个东西很长一段时间了,我希望重新审视它会有所帮助。

谢谢,洛根

floorMap = [[000,000,000,000,000,999,999,999,999,999],
[000,000,999,000,999,000,000,000,999,999],
[000,000,999,000,999,000,000,000,999,999],
[000,000,000,000,999,000,000,000,999,999],
[999,000,000,000,999,000,999,999,999,999],
[999,000,000,000,000,000,999,000,000,999],
[999,000,000,000,999,999,999,000,000,999],
[999,000,999,000,000,000,999,000,000,999],
[999,000,999,999,999,000,000,000,000,999],
[999,999,999,999,999,999,999,999,000,000]]
robotX=0
robotY=0

goalX=9
goalY=9

currentNum=0

wall=999
uncalculated=000

floorMap[robotX][robotY]=1


def changeSurroundings(X, Y):
#left
if(floorMap[X-1][Y]==000):
floorMap[X-1][Y]=currentNum
#right
if(floorMap[X+1][Y]==000):
floorMap[X+1][Y]=currentNum
#up
if(floorMap[X][Y-1]==000):
floorMap[X][Y-1]=currentNum
#down
if(floorMap[X][Y+1]==000):
floorMap[X][Y+1]=currentNum

def printMap():
i=0
while(i<len(floorMap)):
print floorMap[i]
print ""
i+=1
print ""
print ""



#------------------THIS IS WHERE THE PROBLEM IS--------------

while(floorMap[goalX][goalY]==0):
x=0
y=0
while(x<len(floorMap[0])):
while(y<len(floorMap)):
if(floorMap[x][y] > 000 and floorMap[x][y] < 999):
currentNum=floorMap[x][y]+1
changeSurroundings(x,y)
printMap()

y+=1
x+=1

最佳答案

x=0
y=0
while(x<len(floorMap[0])):
while(y<len(floorMap)):
...
y+=1
x+=1

这里的问题是,一旦内层循环用完了 y 值,它将在外层循环完成之前用尽,因为您没有重置 y对于每个内部循环。

只需将 y=0 行移动到外层循环中:

x=0
while(x<len(floorMap[0])):
y=0
while(y<len(floorMap)):
...
y+=1
x+=1

关于python - 试图解决迷宫(波前算法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20606575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com