[英]DFS incorerct output using python
I asked a similar question but after incorporating changes also it is giving incorrect output, please help!
我问了一个类似的问题,但是合并更改后它也给出了错误的输出,请帮忙!
Previous Question Depth First Search in python Error : Key Error 7 上一个问题 深度优先搜索python错误:关键错误7
Current Code : 当前代码:
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))
your working too hard ... DFS is easy to implement 您的工作太辛苦了... 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))
if you want the output to match exactly as you have it you will need to change 如果您希望输出与您所拥有的完全匹配,则需要进行更改
stack.extend(children)
to 至
stack.extend(children[::-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.