我想寫一個矩形網格的DFS,我從某個(x,y)座標開始,必須達到目標座標(xg,yg)。我需要我的函數返回這實際上是我採取的路線清單的路徑,像存儲python的深度優先搜索路徑
到目前爲止我的代碼是這樣的
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存儲路徑的邏輯。請幫忙 !!
請正確縮進您的代碼,以便我們可以按照您的想法。應該將所有代碼段放在'depthFirstSearch'內嗎? – jsbueno
希望這會說清楚。早點對不起! – OneMoreError
你的問題不是很清楚。您的意思是說,當搜索到達死衚衕時,路徑需要包括回溯? – Gene