我问了一个类似的问题,但在合并更改后也提供了不正确的输出,请帮忙!
上一个问题 Depth First Search in python Error : Key Error 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))
答案 0 :(得分:1)
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])