我们有一个G =(V,E)和一组节点(n1,n2,n3,...)。我想使用dfs查找包含集合中所有节点的路径。我们也不希望路径包含一个循环 例如,如果我们有set(n1,n3,n4),则可以接受以下路径。
但以下路径不可接受
如何修改bfs算法来实现这个? 这是我的代码:
setOfNodes = [1,3,4,5,7,8]
def bfs_edges(G, source, reverse=False):
if reverse and isinstance(G, nx.DiGraph):
neighbors = G.predecessors_iter
else:
neighbors = G.neighbors_iter
visited = set([source])
queue = deque([(source, neighbors(source))])
while queue:
parent, children = queue[0]
try:
child = next(children)
if child not in visited:
yield parent, child
visited.add(child)
queue.append((child, neighbors(child)))
except StopIteration:
queue.popleft()