【问题标题】:Find all paths from start to end node using BFS使用 BFS 查找从开始到结束节点的所有路径
【发布时间】:2020-11-03 16:26:57
【问题描述】:

使用下面的 BFS 实现,我们如何修改程序以存储从开始到结束节点的所有路径?有什么想法吗?

def bfs(graph_to_search, start, end):
    queue = [[start]]
    visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)
                new_path.append(current_neighbour)
                queue.append(new_path)

            # Mark the vertex as visited
            visited.add(vertex)

【问题讨论】:

    标签: python python-3.x data-structures breadth-first-search


    【解决方案1】:

    也许这样的事情可以奏效。我认为在检查节点是否被访问时,您将从结果中排除许多路径,仅仅是因为它们包含相同的节点。我将其更改为添加访问的整个路径,并改为检查。还创建了一个空列表results,如果找到最终节点,我们将附加到该列表中。您的代码将在找到最后一个节点的那一刻从函数返回,并且不会探索并找到剩余的路径。让我知道这是否有效!

    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()
        results = []
    
        while queue:
            # Gets the first path in the queue
            path = queue.pop(0)
    
            # Gets the last node in the path
            vertex = path[-1]
    
            # Checks if we got to the end
            if vertex == end:
                results.append(path)
                continue
            # We check if the current path is already in the visited nodes set in order not to recheck it
            elif path not in visited:
                # enumerate all adjacent nodes, construct a new path and push it into the queue
                for current_neighbour in graph_to_search.get(vertex, []):
                    new_path = path.copy()
                    new_path.append(current_neighbour)
                    queue.append(new_path)
    
                # Mark the vertex as visited
                visited.add(path)
          return results
    

    您还可以将queue 中的元素保存为包含当前顶点和上一个路径的元组,就像这样。可能更具可读性。

    queue = [(start, [])]
    vertex, path = queue.pop(0)
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多