应用顶点
地图交叉路口公路
网络路由器网络连接
任务调度任务优先级限制
套汇货币汇率

4.4.2 加权有向图的数据结构

public class DirectedEdge
DirectedEdge(int v, int w, double weight) double weight()边的权重
int from()指出这条边的顶点
int to()这条边指向的顶点
String toString()对象的字符串表示
public class EdgeWeightedDigraph
EdgeWeightedDigraph(int V)含有 V 个顶点的空有向图
EdgeWeightedDigraph(In in)从输入流中读取图的构造函数
int V()顶点总数
int E()边的总数
void addEdge(DirectedEdge e)将 e 添加到该有向图中
Iterable adj(int v)从 v 指出的边
Iterable edges()该有向图中的所有边
String toString()对象的字符串表示
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class DirectedEdge{
    private final int v; // 边的起点
    private final int w; // 边的终点
    private final double weight; // 边的权重
    public DirectedEdge(int v, int w, double weight){
        this.v = v;
        this.w = w;
        this.weight = weight;
    }
    public double weight(){ return weight; }
    public int from(){ return v; }
    public int to(){ return w; }
    public String toString(){ return String.format("%d->%d %.2f", v, w, weight); }
}

public class EdgeWeightedDigraph{
    private final int V;//顶点总数
    private int E;//边的总数
    private Bag<DirectedEdge>[] adj;//邻接表
    public EdgeWeightedDigraph(int V){
        this.V = V;
        this.E = 0;
        adj=(Bag<DirectedEdge>[]) new Bag[V];
        for(int v=0;v<V;v++)
            adj[v]=new Bag<DirectedEdge>();
    }
    public EdgeWeightedDigraph(In in)

    public int V(){return V;}
    public int E(){return E;}
    public void addEdge(DirectedEdge e){
        adj[e.from()].add(e);
        E++;
    }
    public Iterable<DirectedEdge> adj(int v){return adj[v];}
    public Iterable<DirectedEdge> edges(){
        Bag<DirectedEdge> bag = new Bag<DirectedEdge>();
        for(int v=0;v<V;v++)
            for(DirectedEdge e:adj[v])
                bag.add(e);
        return bag;
    }
}

4.4.2.1 最短路径的 API

public class SP
SP(EdgeWeightedDigraph G, int s)构造函数
double distTo(int v)从顶点 s 到 v 的距离,如果不存在则路径为无穷大
boolean hasPathTo(int v)是否存在从顶点 s 到 v 的路径
Iterable pathTo(int v)从顶点 s 到 v 的路径,如果不存在则为null

4.4.2.3 最短路径的数据结构

  • 最短路径树中的边。和深度优先搜索、广度优先搜索和 Prim 算法一样,使用一个由顶点索引的 DirectedEdge 对象的父链接数组 edgeTo[] ,其中 edgeTo[v] 的值为树中连接 v 和它的父结点的边(也是从 s 到 v 的最短路径上的最后一条边)。
  • 到达起点的距离 。我们需要一个由顶点索引的数组 distTo[] ,其中distTo[v] 为从 s 到 v 的已知最短路径的长度。

4.4.2.4 边的松弛

4.4.2.5 顶点的松弛