我有一个定向网络如下。
现在,我想获得该图的所有可能的4个长度和5个长度路径(其中起始和结束路径都是B)
4个长度路径的示例是;
5个长度路径的示例是;
我尝试使用广度优先搜索(BFS)来解决这个问题。似乎大多数BFS算法的代码都不能满足我的要求。那是;
我目前的代码如下:
graph = {'A': ['B'],
'B': ['A','C', 'B'],
'C': ['B']}
# visits all the nodes of a graph (connected component) using BFS
def bfs_connected_component(graph, start):
# keep track of all visited nodes
explored = []
# keep track of nodes to be checked
queue = [start]
# keep looping until there are nodes still to be checked
while queue:
# pop shallowest node (first node) from queue
node = queue.pop(0)
if node not in explored:
# add node to list of checked nodes
explored.append(node)
neighbours = graph[node]
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
return explored
bfs_connected_component(graph,'A')
我想知道是否有任何我可以使用的python库,或者有一种方法可以修改BFS来解决这个问题。
如果需要,我很乐意提供更多示例:)
答案 0 :(得分:2)
当搜索所有组合结果时,我发现python中的递归生成器与其他方法(例如递归函数或基于堆栈的等价物)相比,提供了更紧凑和易懂的代码。
我们正在寻找固定node
的{{1}}到goal
的所有路径。列表length
用作累加器,在基本情况下,它成为通过path
的1路径的前缀。
node
长度为4的路径:
def all_paths(graph, node, goal, length, path=[]):
if length == 0 and node == goal:
yield path + [node]
elif length > 0:
for n in graph[node]:
yield from all_paths(graph, n, goal, length - 1, path + [node])
长度为5的路径:
>>> print(*all_paths(graph, 'B', 'B', 4), sep='\n')
['B', 'A', 'B', 'A', 'B']
['B', 'A', 'B', 'C', 'B']
['B', 'A', 'B', 'B', 'B']
['B', 'C', 'B', 'A', 'B']
['B', 'C', 'B', 'C', 'B']
['B', 'C', 'B', 'B', 'B']
['B', 'B', 'A', 'B', 'B']
['B', 'B', 'C', 'B', 'B']
['B', 'B', 'B', 'A', 'B']
['B', 'B', 'B', 'C', 'B']
['B', 'B', 'B', 'B', 'B']