【发布时间】:2021-04-20 17:30:59
【问题描述】:
我正在尝试编写深度优先搜索算法,该算法将找到代理(黑色立方体所在的位置)到右侧路径底部出口的路径形式。但是我编写的算法会作为找到的路径的一部分在自身上循环。如何实现不执行此操作的 DFS 算法?
关于我做错了什么有什么想法吗?
非常感谢您的帮助。
谢谢 世界是什么样子的:
深度优先搜索路径规划的结果:
我的代理类代码:
class Agent(turtle.Turtle):
def __init__(self, location, endPoint, world):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("black")
self.penup()
self.speed(0)
# Variables
self._bump = 0
self._location = location
self._endPoint = endPoint
self._world = world
self._map = dict()
def dfs_paths(self, start, goal, path=None):
if path is None:
path = [start]
if start == goal:
yield path
for next in self._map[tuple(start)] - set(path):
yield from dfs_paths(next, goal, path + [next])
def _planPath(self, node, visited=None):
if visited is None:
visited = [node]
self._map[tuple(node)] = self._world.testDirections(node)
if node not in visited:
visited.append(tuple((node)))
print("Visited = " + str(visited))
for neighbour in self._map[tuple((node))]:
print("Neighbour = " + str(neighbour))
if neighbour == self._endPoint:
visited.append(neighbour)
print("Here 1...")
return [node, neighbour]
else:
path = self._planPath(neighbour,visited)
if path:
print("Here 2...")
return [node] + path
【问题讨论】:
-
现在是学习how to debug small programs 和to use a debugger 的好时机,逐步检查您的代码并观察每一行代码的作用。通过将这些中间结果与预期结果进行比较,确定您的程序与您的预期有何不同。从那里向后工作以缩小问题的原因。如果您仍然对代码的行为感到困惑,请提出一个特定 问题。转储您的代码并期望其他人为您调试它是不行的。 minimal reproducible example
-
我不是要求它被配音,我不知道如何实现深度优先搜索,它不会自我循环。
-
那是要求它被调试。请提供minimal reproducible example
-
@MahmoudYassine 如果你跟踪访问过的节点,应该很容易防止循环
-
@AbhinavMathur 我相信我正在使用 _planPath 函数中的变量“visited”跟踪访问过的节点。
标签: python algorithm search gridworld