我正在尝试编写一个深度优先搜索算法,该算法将找到代理(黑色立方体所在)到右侧路径底部出口的路径形式。但是我编写的算法会作为找到的路径的一部分在自身上循环。如何实现不这样做的 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