[英]DFS incorerct output using python
我問了一個類似的問題,但是合並更改后它也給出了錯誤的輸出,請幫忙!
上一個問題 深度優先搜索python錯誤:關鍵錯誤7
當前代碼:
output=[]
graph = {
1:[2,3],
2:[4,5],
3:[6,7],
4:[],
5:[],
6:[],
7:[]
}
def dfs(graph,root):
stack=[]
visited=set()
stack.append(root)
output.append(str(root))
visited.add(root)
while not(stack==[]):
for item in graph[root]:
if item not in visited:
stack.append(item)
visited.add(item)
output.append(str(item))
if set(graph[item]).union(visited)==visited:
stack.pop(-1)
if not(stack==[]):
root=stack[len(stack)-1]
else:
break
continue
root=item
dfs(graph,1)
print(" ".join(output))
您的工作太辛苦了... DFS易於實現
output=[]
graph = {
1:[2,3],
2:[4,5],
3:[6,7],
4:[],
5:[],
6:[],
7:[]
}
def dfs(graph,root):
stack=[]
visited=set()
stack.append(root)
while stack:
node = stack.pop() #remove last
if node in visited:
continue
visited.add(node)
output.append(str(node))
children = graph[node]
stack.extend(children)
dfs(graph,1)
print(" ".join(output))
如果您希望輸出與您所擁有的完全匹配,則需要進行更改
stack.extend(children)
至
stack.extend(children[::-1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.