0402算法理论基础和Dijkstra算法-最短路径-加权有向图-数据结构和算法(Java)

1 最短路径算法的理论基础

边的放松操作时一项非常容易实现的重要操作,它是实现最短路径算法的基础。同时,它也是理解这个算法的理论基础并使我们能够完整地证明算法的正确性。

1.1 最优性条件

以下命题证明判断路径是否为最短路径的全局条件与在放松一条边所检测的局部条件是等价的。

命题P(最短路径的最优性条件)。G为一幅加权有向图,顶点s是G中的起点,distTo[]是顶点索引的数组,保存路径的长度。对于从s可达的所有顶点v,distTo[v]的值是从s到v的某条路径的长度,对于从s不可达的顶点v,该值为无穷大。

当且仅当对于从v到w到任意一条边e,这些值满足 d i s t T o [ w ] ≤ d i s t T o [ v ] + e . w e i g h t distTo[w]\le distTo[v]+e.weight distTo[w]distTo[v]+e.weight时,它们时最短路径的长度。

证明。假设distTo[w]时从s到w到最短路径。如果对于某条从v到w到边e有 d i s t T o [ w ] > d i s t T o [ v ] + e . w e i g h t distTo[w]\gt distTo[v]+e.weight distTo[w]>distTo[v]+e.weight,那么从s到w(经过v)切经过e到路径长度比人小于distTo[w],与假设相矛盾。因此最优性条件时必要的。

证明最优性条件的充分性,假设w时从s可达的且 s = v 0 − > v 1 − > v 2 − > ⋯ − > v k = w s=v_0->v_1->v_2->\cdots->v_k=w s=v0>v1>v2>>vk=w是从s到w到最短路径其权重为 O P T s w OPT_{sw} OPTsw。对于 1 到 k 之间的 i ,令 e i 表示 v i − 1 到 v i 的边 1到k之间的i,令e_i表示v_{i-1}到v_i的边 1k之间的i,令ei表示vi1vi的边。根据最优性条件,可以得到以下不等式:
d i s t T o [ w ] = { d i s t T o [ v k ] ≤ d i s t T o [ v k − 1 ] + e k . w e i g h t + d i s t T o [ v k − 1 ] ≤ d i s t T o [ v k − 2 ] + e k − 1 . w e i g h t + ⋯ + d i s t T o [ v i ] ≤ d i s t T o [ v i − 1 ] + e i . w e i g h t + ⋯ + d i s t T o [ v 1 ] ≤ d i s t T o [ s ] + e 1 . w e i g h t distTo[w]= \begin{cases} distTo[v_k]\le distTo[v_{k-1}]+e_k.weight\\ +distTo[v_{k-1}]\le distTo[v_{k-2}]+e_{k-1}.weight\\ +\cdots\\ +distTo[v_i]\le distTo[v_{i-1}]+e_i.weight\\ +\cdots\\ +distTo[v_1]\le distTo[s]+e_1.weight \end{cases} distTo[w]= distTo[vk]distTo[vk1]+ek.weight+distTo[vk1]distTo[vk2]+ek1.weight++distTo[vi]distTo[vi1]+ei.weight++distTo[v1]distTo[s]+e1.weight
d i s t T o [ w ] = 0.0 distTo[w]=0.0 distTo[w]=0.0,带入,得 d i s t T o [ w ] ≤ e 1 . w e i g h t + e 2 . w e i g h t + ⋯ + e k . w e i g h t = O P T s w distTo[w]\le e_1.weight+e_2.weight+\cdots+e_k.weight=OPT_{sw} distTo[w]e1.weight+e2.weight++ek.weight=OPTsw

distTo[w]为从s到w的某条路径长度,因此不可能比最短路径还短,所以有:

O P T s w ≤ d i s t T o [ w ] ≤ O P T s w OPT_{sw}\le distTo[w]\le OPT_{sw} OPTswdistTo[w]OPTsw

即满足最优性条件distTo[w]即为最短路径。

1.2 通用算法

由最优性条件可以得到一个最短路径的通用算法,非负权重情况:

命题Q(通用最短路径算法)。将distTo[s]初始化为0,其他distTo[]元素初始化为无穷大继续如下操作:

放松G中的任意边,直到不存在有效边为止。

证明:方式边v->w边人会将distTo[w]的值设为从s到w到某条路径的长度(切将edgeTo[w]设为该路径上的最好一条边)。对于从s可达的任意顶点w,只要distTo[w]仍然是无穷大,到达w的最短路径上某条边肯定仍然上有效的,因此算法操作会不断继续,直到由s可达的每个顶点的distTo[]的值均变为到达该顶点的某条路径的长度。对于已经找到最短路径的任意顶点v,在算法的计算过程中distTo[v]的值都是从s到v的某条路径的长度切必然上单调递减的。因此,它递减的次数必然是有限的。当不存在有效边的时候,命题P成立。

将最优性条件和通用算法一起学习原因是,通用算法没有指定边的放松顺序。因此,要证明这些算法能通过计算得到最短路径,只要证明它们都会放松所有的边直到所有边都失效即可。

2 Dijkstra算法

之前我们学习加权无向图最小生成树的Prim算法:构造最小生成树的每一步都想这棵树中添加一条新的边。Dijkstra算法采用了类似的方法来计算最短路径树。首先将distTo[s]初始化为0,distTo[]其他元素初始化为正无穷。然后将最小的非树顶点放松并加入树中,如此这般,直到所有顶点都在树中或者所有的非树顶点的distTo[]值均为无穷大。

2.1 数据结构

除了distTo[]和edgeTo[]数组之外还需要一条索引优先队列qp,以保存需要被放松的顶点并确定下一个要放松的顶点。

  • edgeTo[]中的元素所对应的可达顶点构成了一颗最短路径树。

2.2 算法实现

/******************************************************************************
 *  Compilation:  javac DijkstraSP.java
 *  Execution:    java DijkstraSP input.txt s
 *  Dependencies: EdgeWeightedDigraph.java IndexMinPQ.java Stack.java DirectedEdge.java
 *  Data files:   https://algs4.cs.princeton.edu/44sp/tinyEWD.txt
 *                https://algs4.cs.princeton.edu/44sp/mediumEWD.txt
 *                https://algs4.cs.princeton.edu/44sp/largeEWD.txt
 *
 *  Dijkstra's algorithm. Computes the shortest path tree.
 *  Assumes all weights are non-negative.
 *
 *  % java DijkstraSP tinyEWD.txt 0
 *  0 to 0 (0.00)  
 *  0 to 1 (1.05)  0->4  0.38   4->5  0.35   5->1  0.32   
 *  0 to 2 (0.26)  0->2  0.26   
 *  0 to 3 (0.99)  0->2  0.26   2->7  0.34   7->3  0.39   
 *  0 to 4 (0.38)  0->4  0.38   
 *  0 to 5 (0.73)  0->4  0.38   4->5  0.35   
 *  0 to 6 (1.51)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   
 *  0 to 7 (0.60)  0->2  0.26   2->7  0.34   
 *
 *  % java DijkstraSP mediumEWD.txt 0
 *  0 to 0 (0.00)  
 *  0 to 1 (0.71)  0->44  0.06   44->93  0.07   ...  107->1  0.07   
 *  0 to 2 (0.65)  0->44  0.06   44->231  0.10  ...  42->2  0.11   
 *  0 to 3 (0.46)  0->97  0.08   97->248  0.09  ...  45->3  0.12   
 *  0 to 4 (0.42)  0->44  0.06   44->93  0.07   ...  77->4  0.11   
 *  ...
 *
 ******************************************************************************/

package edu.princeton.cs.algs4;


/**
 *  The {@code DijkstraSP} class represents a data type for solving the
 *  single-source shortest paths problem in edge-weighted digraphs
 *  where the edge weights are non-negative.
 *  <p>
 *  This implementation uses <em>Dijkstra's algorithm</em> with a
 *  <em>binary heap</em>. The constructor takes
 *  &Theta;(<em>E</em> log <em>V</em>) time in the worst case,
 *  where <em>V</em> is the number of vertices and <em>E</em> is
 *  the number of edges. Each instance method takes &Theta;(1) time.
 *  It uses &Theta;(<em>V</em>) extra space (not including the
 *  edge-weighted digraph).
 *  <p>
 *  This correctly computes shortest paths if all arithmetic performed is
 *  without floating-point rounding error or arithmetic overflow.
 *  This is the case if all edge weights are integers and if none of the
 *  intermediate results exceeds 2<sup>52</sup>. Since all intermediate
 *  results are sums of edge weights, they are bounded by <em>V C</em>,
 *  where <em>V</em> is the number of vertices and <em>C</em> is the maximum
 *  weight of any edge.
 *  <p>
 *  For additional documentation,    
 *  see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of    
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. 
 *
 *  @author Robert Sedgewick
 *  @author Kevin Wayne
 */
public class DijkstraSP {
    private double[] distTo;          // distTo[v] = distance  of shortest s->v path
    private DirectedEdge[] edgeTo;    // edgeTo[v] = last edge on shortest s->v path
    private IndexMinPQ<Double> pq;    // priority queue of vertices

    /**
     * Computes a shortest-paths tree from the source vertex {@code s} to every other
     * vertex in the edge-weighted digraph {@code G}.
     *
     * @param  G the edge-weighted digraph
     * @param  s the source vertex
     * @throws IllegalArgumentException if an edge weight is negative
     * @throws IllegalArgumentException unless {@code 0 <= s < V}
     */
    public DijkstraSP(EdgeWeightedDigraph G, int s) {
        for (DirectedEdge e : G.edges()) {
            if (e.weight() < 0)
                throw new IllegalArgumentException("edge " + e + " has negative weight");
        }

        distTo = new double[G.V()];
        edgeTo = new DirectedEdge[G.V()];

        validateVertex(s);

        for (int v = 0; v < G.V(); v++)
            distTo[v] = Double.POSITIVE_INFINITY;
        distTo[s] = 0.0;

        // relax vertices in order of distance from s
        pq = new IndexMinPQ<Double>(G.V());
        pq.insert(s, distTo[s]);
        while (!pq.isEmpty()) {
            int v = pq.delMin();
            for (DirectedEdge e : G.adj(v))
                relax(e);
        }

        // check optimality conditions
        assert check(G, s);
    }

    // relax edge e and update pq if changed
    private void relax(DirectedEdge e) {
        int v = e.from(), w = e.to();
        if (distTo[w] > distTo[v] + e.weight()) {
            distTo[w] = distTo[v] + e.weight();
            edgeTo[w] = e;
            if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
            else                pq.insert(w, distTo[w]);
        }
    }

    /**
     * Returns the length of a shortest path from the source vertex {@code s} to vertex {@code v}.
     * @param  v the destination vertex
     * @return the length of a shortest path from the source vertex {@code s} to vertex {@code v};
     *         {@code Double.POSITIVE_INFINITY} if no such path
     * @throws IllegalArgumentException unless {@code 0 <= v < V}
     */
    public double distTo(int v) {
        validateVertex(v);
        return distTo[v];
    }

    /**
     * Returns true if there is a path from the source vertex {@code s} to vertex {@code v}.
     *
     * @param  v the destination vertex
     * @return {@code true} if there is a path from the source vertex
     *         {@code s} to vertex {@code v}; {@code false} otherwise
     * @throws IllegalArgumentException unless {@code 0 <= v < V}
     */
    public boolean hasPathTo(int v) {
        validateVertex(v);
        return distTo[v] < Double.POSITIVE_INFINITY;
    }

    /**
     * Returns a shortest path from the source vertex {@code s} to vertex {@code v}.
     *
     * @param  v the destination vertex
     * @return a shortest path from the source vertex {@code s} to vertex {@code v}
     *         as an iterable of edges, and {@code null} if no such path
     * @throws IllegalArgumentException unless {@code 0 <= v < V}
     */
    public Iterable<DirectedEdge> pathTo(int v) {
        validateVertex(v);
        if (!hasPathTo(v)) return null;
        Stack<DirectedEdge> path = new Stack<DirectedEdge>();
        for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {
            path.push(e);
        }
        return path;
    }


    // check optimality conditions:
    // (i) for all edges e:            distTo[e.to()] <= distTo[e.from()] + e.weight()
    // (ii) for all edge e on the SPT: distTo[e.to()] == distTo[e.from()] + e.weight()
    private boolean check(EdgeWeightedDigraph G, int s) {

        // check that edge weights are non-negative
        for (DirectedEdge e : G.edges()) {
            if (e.weight() < 0) {
                System.err.println("negative edge weight detected");
                return false;
            }
        }

        // check that distTo[v] and edgeTo[v] are consistent
        if (distTo[s] != 0.0 || edgeTo[s] != null) {
            System.err.println("distTo[s] and edgeTo[s] inconsistent");
            return false;
        }
        for (int v = 0; v < G.V(); v++) {
            if (v == s) continue;
            if (edgeTo[v] == null && distTo[v] != Double.POSITIVE_INFINITY) {
                System.err.println("distTo[] and edgeTo[] inconsistent");
                return false;
            }
        }

        // check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight()
        for (int v = 0; v < G.V(); v++) {
            for (DirectedEdge e : G.adj(v)) {
                int w = e.to();
                if (distTo[v] + e.weight() < distTo[w]) {
                    System.err.println("edge " + e + " not relaxed");
                    return false;
                }
            }
        }

        // check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight()
        for (int w = 0; w < G.V(); w++) {
            if (edgeTo[w] == null) continue;
            DirectedEdge e = edgeTo[w];
            int v = e.from();
            if (w != e.to()) return false;
            if (distTo[v] + e.weight() != distTo[w]) {
                System.err.println("edge " + e + " on shortest path not tight");
                return false;
            }
        }
        return true;
    }

    /**
    * 校验顶点v
    */
    private void validateVertex(int v) {
        int V = distTo.length;
        if (v < 0 || v >= V)
            throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
    }

}

2.3 理解

命题R。Dijkstra算法能够解决边权重非负的加权有向图的单起点最短路径问题。

证明:如果v是从起点可达的,那么所有v->w的边都只会被放松一次。当v被放松时,必有distTo[w] ≤ \le distTo[v]+e.weight()。该不等式在算法结束前都会成立,因此distTo[w]只会变小(放松操作只会减小distTo[]的值)而distTo[v]则不会变(因为边的权重非负且在每一步中算法都会选择distTo[]最小的顶点,之后的放松操作不可能使任何distTo[]的值小于distTo[v])。因此,在所有从s可达的顶点均被添加到树中之后,最短路径的最优性条件成立,即命题P成立。

我们可以从另外一个角度理解它,已知树结点所对应的distTo[]值均为最短路径长度。对于优先队列中的任意顶点w,distTo[w]是从s到w的最短路径长度,该路径上的中间顶点在树中且路径结束于横切边edgeTo[w]。优先级最小的顶点的distTo[]值就是最短路径的权重,它不会小于已经被放松过的任意顶点的最短路径的权重,也不会大于未被放松过的任意顶点的最短路径的权重。这个顶点就是下一个要被放松的顶点。所有从s可达的顶点都会按照最短路径的权重顺序被放松。

命题R(续)。在一幅含有V个顶点和E条边的加权有向图中,使用Dijkstra算法计算根结点为给定起点的最短路径树所需的空间与V成正比,时间与 E log ⁡ V E\log V ElogV成正比(最坏情况)。

结语

如果小伙伴什么问题或者指教,欢迎交流。

❓QQ:806797785

⭐️源代码仓库地址:https://gitee.com/gaogzhen/algorithm

参考链接:

[1][美]Robert Sedgewich,[美]Kevin Wayne著;谢路云译.算法:第4版[M].北京:人民邮电出版社,2012.10.p420-425.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaog2zh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值