algorithm - 如何使用 BFS 按顺序获取包含某些给定节点的路径?

标签 algorithm graph-algorithm

<分区>

我有一个带有未加权边的图,其中每个节点都标有字母“a”到“z”。

我想修改 BFS 算法以获得按顺序包含字母“c”、“o”、“d”、“e”的最短路径。这四个字母之间可能还有其他字母。您有起始节点“a”和结束节点“b”。您可以假设它始终是按顺序包含这四个字母的路径。如何修改 BFS 以满足该条件?

最佳答案

如果你知道如何用 BFS 找到两个节点之间的最短路径,那么问题可以解决如下:

  • 找到从ac的最短路径
  • 找到从co的最短路径
  • 找到从od的最短路径
  • 找到从de的最短路径
  • 找到从eb的最短路径
  • 连接上述 5 条路径,得到一条从 ab 的路径。

这是 Python 中的一个实现:

class Node:
    def __init__(self, name):
        self.name = name
        self.neighbors = []

    def link(self, node): 
        # The edge is undirected: implement it as two directed edges
        self.neighbors.append(node)
        node.neighbors.append(self)

    def shortestPathTo(self, target):
        # A BFS implementation which retains the paths
        queue = [[self]]
        visited = set()
        while len(queue):
            path = queue.pop(0) # Get next path from queue (FIFO)
            node = path[-1] # Get last node in that path
            for neighbor in node.neighbors:
                if neighbor == target:
                    # Found the target node. Return the path to it
                    return path + [target]
                # Avoid visiting a node that was already visited
                if not neighbor in visited:
                    visited.add(neighbor)
                    queue.append(path + [neighbor])

# Create the nodes of the graph (indexed by their names)
graph = {}
for letter in 'abcdefo':
    graph[letter] = Node(letter)

# Create the undirected edges
for start, end in ['ab','ae','bc','be','bo','df','ef','fo']:
    graph[start].link(graph[end])

# Concatenate the shortest paths between each of the required node pairs 
start = 'a'
path = [graph['a']]
for end in ['c','o','d','e','b']:
    path.extend( graph[start].shortestPathTo(graph[end])[1:] )
    start = end

# Print result: the names of the nodes on the path
print([node.name for node in path])

代码中创建的图表如下所示:

enter image description here

输出是:

['a', 'b', 'c', 'b', 'o', 'f', 'd', 'f', 'e', 'b']

关于algorithm - 如何使用 BFS 按顺序获取包含某些给定节点的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860862/

相关文章:

java - 使用 jGraphT 读取图形 GML 文件

c++ - 为回文遍历网格

c# - 如何在 C# 中合并列表中的日期范围

Python 算法/函数 : return all of the operational combinations of the digits of an input number which equal a target number

algorithm - 遍历欧拉回路中的所有边并打印节点

algorithm - 基于相邻节点计算节点值的图形算法

java - Java中的最短路径实现

划分区域的算法,使每个给定点都位于其绘图的中心

algorithm - 该算法的最坏情况运行时间(如何证明)?

java - 霍夫变换后如何显示清晰的结果?