BFS实现,用于检查路径是否包含一组没有循环的节点

时间:2018-02-13 18:38:40

标签: python python-3.x networkx breadth-first-search

我们有一个G =(V,E)和一组节点(n1,n2,n3,...)。我想使用dfs查找包含集合中所有节点的路径。我们也不希望路径包含一个循环 例如,如果我们有set(n1,n3,n4),则可以接受以下路径。

enter image description here

但以下路径不可接受

enter image description here

如何修改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()

0 个答案:

没有答案