【发布时间】:2026-01-25 15:55:01
【问题描述】:
我有下面的深度优先搜索代码:
def dfs(graph, vertex):
visited = set()
stack = [vertex]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex])
return visited
def main():
test_graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
print(dfs(test_graph, 'A'))
if __name__ == '__main__':
main()
在每次执行时,我都会得到不同的输出。
我是否可以进行任何更改以使输出始终以 vertex 的值开头(在本例中为 A)?
【问题讨论】:
标签: python graph depth-first-search