繁体   English   中英

未加权双向图上的广度优先搜索

[英]Breadth First Search on an unweighted bidirectional graph

我一直在尝试使用BFS查找2个节点之间的最短路径。 我尝试查看教程和在线阅读资料,但对我来说,这些内容都不是很清楚。 我目前只能遍历该图,但是我不确定是否需要进行哪些检查才能找到图中两个节点之间的最小路径。 该图是未加权的并且是双向的。 这是我使用BFS遍历图中所有节点的代码。

def bredthfirstsearch(start, end, graph):
    queue = [start]
    visited = [False]*(roads+1) #marks if a node has been visited
    visited[start] = True
    while len(queue) != 0:
        # source node popped and later used to find neighboring nodes
        node = queue.pop(0)

        for item in graph[node]:
            # if the node has not been found previously
            if visited[item[0]] == False:
                queue.append(item[0]) # it is added to the queue for future checking on its neighbors 
                visited[item[0]] = True #node then set to true

现在,我可能需要一个额外的数组来存储最短路径,但是我不确定该怎么做。 非常感谢。

BFS将帮助您找到特定节点的所有最短路径。 如果要使用BFS查找图形中每对节点之间的最小路径,则几乎需要从每个节点(几乎每个节点都运行BFS,因为已经计算了一些叶子)。

这是找到两个节点之间距离的方法。 在顶点a(任意顶点)上使用BFS,您将能够找到到其他顶点的所有最短路径(距离)。 要计算距离,您将需要一个“液位计”。 这是一个伪代码,可以帮助您:

q = new Queue()
dist_array = new Array(N) //and Set each value to infinity
distance=0
q.enqueue(a) //a is the selected node
dist_array[a] = 0
while q not empty:
    v = q.dequeue()
    ++distance
    for each neighbor x of v:
        if distance_array[x] < infinity:
             continue
        d[x] = distance
        q.enqueue(x)

可以说您的图形在以下情况下为G =(V,E):

  • V = {a,b,c,d,e,f},| V | = N = 6
  • E = {(a,b),(a,c),(a,e),(b,d),(b,e),(d,f)},| E | = M = 6

如果我们在图形上运行此代码,我们将得到以下结果

dist=1: a->b, a->c, a->e
dist=2: a->d
dist=3: a->f

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM