【问题标题】:Depth First Search Output Changes on Every Run每次运行的深度优先搜索输出变化
【发布时间】: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


    【解决方案1】:

    在 Python 中,set 没有排序。您可以使用 collections.OrderedDict 来保持键的插入顺序,同时让 not in 在 O(1) 中工作,就像在一组中一样:

    from collections import OrderedDict
    
    def dfs(graph, vertex):
        visited = OrderedDict()
        stack = [vertex]
        while stack:
            vertex = stack.pop()
            if vertex not in visited:
                visited[vertex] = True
                stack.extend(graph[vertex])
        return list(visited.keys())
    
    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()
    

    【讨论】:

      【解决方案2】:

      您的算法很好,每次运行时它都会做同样的事情。问题在于使用set 来返回输出。一组没有顺序,你可能会在不同的运行中得到不同的结果。您可以通过多种方式解决这个问题 - 一种是从集合中创建一个列表并在从 dfs 函数返回之前对其进行排序。

      另一种解决方案是首先使用列表:

      def dfs(graph, vertex):
          visited = []
          stack = [vertex]
          while stack:
              vertex = stack.pop()
              if vertex not in visited:
                  visited.append(vertex)
                  stack.extend(graph[vertex])
      
          return visited
      

      【讨论】: