【问题标题】:Find the most expensive path from s to t using BFS使用 BFS 找到从 s 到 t 的最昂贵路径
【发布时间】:2016-09-12 19:14:22
【问题描述】:

在给定的图形G=(V,E) 中,每条边都有一个成本c(e)。我们有一个起始节点 s 和一个目标节点 t。我们如何使用以下 BFS 算法找到从 s 到 t 的边数最少的最昂贵路径?

BFS(G,s):
    foreach v in V do
        color[v] <- white; parent[v] <- nil
    color[s] <- grey; parent[s] <- s
    BFS-Visit(s)

BFS-Visit(u):
    Q <- empty queue
    Enqueue(Q,u)
    while Q != empty do
        v <- Dequeue(Q)
        foreach w in Adj[v] do
            if color[w] white then
               color[w] <- grey
               parent[w] <- v
               Enqueue(Q,w)
        color[v] <- black 

【问题讨论】:

    标签: algorithm graph-theory breadth-first-search


    【解决方案1】:

    BFS 的属性是距离源 d 的所有节点的集合被考虑在距离 d+1 的所有节点的集合之前。因此,即使节点是灰色的,您也必须更新“最昂贵的路径”:

    BFS(G,s):
        foreach v in V do
            color[v] <- white; parent[v] <- nil; mesp[v] <- -inf
            # mesp[v]: most expensive shortest path from s to v
        color[s] <- grey; parent[s] <- s; mesp[s] <- 0
        BFS-Visit(s)
    
    BFS-Visit(u):
        Q <- empty queue
        Enqueue(Q,u)
        while Q = empty do
            v <- Dequeue(Q)
            foreach w in Adj[v] do
                if color[w] != black and mesp[v] + c(v, w) > mesp[w]:
                   color[w] <- grey
                   mesp[w] = mesp[v] + c(v, w)
                   parent[w] <- v
                   Enqueue(Q,w)
            color[v] <- black
    

    【讨论】:

    • +1 谢谢,我明白了。但我对以给定节点 t 结束的路径感兴趣。所以我们应该停在 t 而不是看它的邻居。如果我们找到到 t 的多条路径,我们如何选择边数最少的路径?
    • @zabware:当v = tmesp[t]会给你答案。这是算法的一种不变量:当指令v &lt;- Dequeue(Q)被执行时,mesp[v]sv的最昂贵最短路径的成本(因此是这种情况v = t)。当Q 为空或到达v 时,您可以结束循环:如果您的图表已连接,则return mesp[t] 在这两种情况下都可以工作。
    • 所以在 mesp[w] = mesp[v] + c(v, w) 之后我可以简单地做 If t = v then return mesp[w] else enqueue(q,w)?跨度>
    • @zabware:不,这可能是错误的,因为在 s 的相同距离内还有其他节点可以改进 mesp[w]。您必须等到到达外部while 循环中的w(例如v &lt;- Dequeue(Q) if (v == t) return mesp[t])。因此,您确信您考虑了到 t 的所有最短路径。
    • @zabware:如果您知道如何使用 BFS 计算最短路径的数量(并了解它的为什么起作用),这是一个非常相似的想法。
    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 2022-01-22
    • 1970-01-01
    • 2012-03-24
    • 2018-08-07
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多