gpt4 book ai didi

python - 为什么迷宫求解器代码不起作用

转载 作者:行者123 更新时间:2023-12-01 04:06:13 29 4
gpt4 key购买 nike

对于错误的格式和大量的代码感到抱歉,我只是一个初学者,不知道如何将错误诊断为较小的代码量。我哪里出错了,它只是返回“在 0, 0 处发现空”并退出。我已经查看了这种性质下的其他代码,无法理解给出的答案,需要对此特定代码进行更多阐述。请帮忙

 grid = [["T", " ", " ", "#", "#", "#"],
["#", "#", " ", " ", " ", "#"],
["#", " ", " ", "#", " ", "#"],
["#", "#", "#", " ", " ", "#"],
["#", "#", " ", " ", "#", " "],
["#", "#", "#", "#", "#", "E"]]

def print_grid():
pr_grid = ""
for key in grid:
for num in key:
pr_grid += str(num)
pr_grid += " "
print pr_grid
pr_grid = ""

print pr_grid

run = True

def main(x, y):
if grid[x][y] == " " or grid[x][y] == "T":
print "Found empty at %d %d" % (x, y)
grid[x][y] = "x"
elif grid[x][y] == "#":
print "Found wall at %d %d" % (x, y)
elif grid[x][y] == "E":
print "Found exit at %d %d" % (x, y)

if y < len(grid)-1:
main(x, y + 1)
if y > 0:
main(x, y - 1)
if x < len(grid[x])-1:
main(x + 1, y)
if x > 0:
main(x - 1, y)


print_grid()

main(0, 0)

print_grid()

最佳答案

没有声称这是否比其他答案更快,但如果您想在找到导出时返回 True/False,那么您可以为每个递归调用维护一个 bool 值。

(此外,您的 print_grid 方法可以更短)

def print_grid():
print "\n".join(' '.join(row) for row in grid)
<小时/>

无论如何,这是我对程序所做的修改。

def main(x, y):
# Check going out of bounds
if y < 0 or y >= len(grid):
return False
if x < 0 or x >= len(grid[y]):
return False

if grid[x][y] == "E":
print "Found exit at %d %d" % (x, y)
return True
elif grid[x][y] == "#":
print "Found wall at %d %d" % (x, y)
return False
elif grid[x][y] == " " or grid[x][y] == "T":
print "Found empty at %d %d" % (x, y)
grid[x][y] = "x"
# no return, we want to continue searching
else: # catch invalid characters
return False

found = False
# "Bubble-up" the results from searching for the exit
# Also limit the search space by keeping track if the exit was found
if y < len(grid)-1 and not found:
found = main(x, y + 1)
if y > 0 and not found:
found = main(x, y - 1)
if x < len(grid[x])-1 and not found:
found = main(x + 1, y)
if x > 0 and not found:
found = main(x - 1, y)

return found

关于python - 为什么迷宫求解器代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545291/

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