我正在尝试为矩形网格编写DFS,其中我从某个(x,y)坐标开始,并且必须达到目标坐标(xg,yg)。我需要我的函数来返回一个路径,这个路径实际上是我已经采取的路线列表,比如
action=['Up','Left','Left','Bottom']
到目前为止我的代码是这样的
def depthFirstSearch():
visited=[] # stores the vertices that I have visited
action=[] # this is what I have to return
stack=Stack() # the general stack used in DFS
forward=Stack() # stores the forward direction
reverse=Stack() # stores the backward direction, in case we need to backtrack
stack.push(getStartState())
while not stack.isEmpty():
tmp=stack.pop()
if(GoalState(tmp)):
return action
if not tmp in visited:
visited.append(tmp)
if not forward.isEmpty():
dirn=forward.pop()
action.append(dirn)
reverse.append(opposite(dirn))
child1=getSuccessors(tmp) # returns all the possible childs and direction as a list
child2=[]
for st in child1:
if not st in visited:
child2.append(st)
if child2:
for state in child2:
stack.push(state[0])
forward.push(state[1])
reverse.push(oppposite(state[1])
elif not child2:
action.append(reverse.pop())
我是python的新手,如果有人可以帮助我,我会非常感激。我有缩进问题。另外,我不太确定我的DFS存储路径的逻辑。请帮忙!!
答案 0 :(得分:0)
这是一篇解释Depth First Search的文章。您执行的操作如下:start
个节点(x,y)
,然后检查您访问的步骤是否已达到goal
(xg,yg)
深度优先搜索的方式是,它维护一个堆栈并将每个被访问的节点推入堆栈并弹出它们并检查它是否是目标。在您的程序中,您必须将该检查步骤写入列表。我希望教程链接可以帮助您入门。