【发布时间】:2023-01-14 23:39:18
【问题描述】:
我目前正在掌握 Python 中的图形遍历。
给定下图:
使用这个字典实现:
graph = {'0': set(['1', '2', '3']),
'1': set(['0','2']),
'2': set(['0','1','4']),
'3': set(['0']),
'4': set(['2'])}
我认为从节点 0 开始的深度优先搜索遍历应该返回 [0,1,2,4,3] 是否正确?
我的 dfs 函数返回 [0,3,1,2,4] 所以我想知道我的实现是否有问题:
def dfs(graph, node,visited=None):
if visited is None:
visited=set()
if node not in visited:
print (node,end=' ')
visited.add(node)
for neighbour in graph[node]:
dfs(graph,neighbour,visited=visited)
dfs(graph,'0')
帮助和建议表示赞赏。
【问题讨论】:
标签: python graph-theory depth-first-search