| 
001002
 003
 004
 005
 006
 007
 008
 009
 010
 011
 012
 013
 014
 015
 016
 017
 018
 019
 020
 021
 022
 023
 024
 025
 026
 027
 028
 029
 030
 031
 032
 033
 034
 035
 036
 037
 038
 039
 040
 041
 042
 043
 044
 045
 046
 047
 048
 049
 050
 051
 052
 053
 054
 055
 056
 057
 058
 059
 060
 061
 062
 063
 064
 065
 066
 067
 068
 069
 070
 071
 072
 073
 074
 075
 076
 077
 078
 079
 080
 081
 082
 083
 084
 085
 086
 087
 088
 089
 090
 091
 092
 093
 094
 095
 096
 097
 098
 099
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 
 | package algs44;
import stdlib.*;
import algs13.Queue;
import algs13.Stack;
/* ***********************************************************************
 *  Compilation:  javac BellmanFordSP.java
 *  Execution:    java BellmanFordSP filename.txt s
 *  Dependencies: EdgeWeightedDigraph.java DirectedEdge.java Queue.java
 *                EdgeWeightedDirectedCycle.java
 *  Data files:   http://algs4.cs.princeton.edu/44sp/tinyEWDn.txt
 *                http://algs4.cs.princeton.edu/44sp/mediumEWDnc.txt
 *
 *  Bellman-Ford shortest path algorithm. Computes the shortest path tree in
 *  edge-weighted digraph G from vertex s, or finds a negative cost cycle
 *  reachable from s.
 *
 *  % java BellmanFordSP tinyEWDn.txt 0
 *  0 to 0 ( 0.00)
 *  0 to 1 ( 0.93)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25   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.26)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25
 *  0 to 5 ( 0.61)  0->2  0.26   2->7  0.34   7->3  0.39   3->6  0.52   6->4 -1.25   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 BellmanFordSP tinyEWDnc.txt 0
 *  4->5  0.35
 *  5->4 -0.66
 *
 *************************************************************************/
public class BellmanFordSP {
  private final double[] distTo;               // distTo[v] = distance  of shortest s->v path
  private final DirectedEdge[] edgeTo;         // edgeTo[v] = last edge on shortest s->v path
  private final boolean[] onQueue;             // onQueue[v] = is v currently on the queue?
  private final Queue<Integer> queue;          // queue of vertices to relax
  private int cost;                      // number of calls to relax()
  private Iterable<DirectedEdge> cycle;  // negative cycle (or null if no such cycle)
  public BellmanFordSP(EdgeWeightedDigraph G, int s) {
    distTo  = new double[G.V()];
    edgeTo  = new DirectedEdge[G.V()];
    onQueue = new boolean[G.V()];
    for (int v = 0; v < G.V(); v++)
      distTo[v] = Double.POSITIVE_INFINITY;
    distTo[s] = 0.0;
    // Bellman-Ford algorithm
    queue = new Queue<>();
    queue.enqueue(s);
    onQueue[s] = true;
    while (!queue.isEmpty() && !hasNegativeCycle()) {
      int v = queue.dequeue();
      onQueue[v] = false;
      relax(G, v);
    }
    assert check(G, s);
  }
  // relax vertex v and put other endpoints on queue if changed
  private void relax(EdgeWeightedDigraph G, int v) {
    for (DirectedEdge e : G.adj(v)) {
      int w = e.to();
      if (distTo[w] > distTo[v] + e.weight()) {
        distTo[w] = distTo[v] + e.weight();
        edgeTo[w] = e;
        if (!onQueue[w]) {
          queue.enqueue(w);
          onQueue[w] = true;
        }
      }
      if (cost++ % G.V() == 0)
        findNegativeCycle();
    }
  }
  // is there a negative cycle reachable from s?
  public boolean hasNegativeCycle() {
    return cycle != null;
  }
  // return a negative cycle; null if no such cycle
  public Iterable<DirectedEdge> negativeCycle() {
    return cycle;
  }
  // by finding a cycle in predecessor graph
  private void findNegativeCycle() {
    int V = edgeTo.length;
    EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V);
    for (int v = 0; v < V; v++)
      if (edgeTo[v] != null)
        spt.addEdge(edgeTo[v]);
    EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(spt);
    cycle = finder.cycle();
  }
  // is there a path from s to v?
  public boolean hasPathTo(int v) {
    return distTo[v] < Double.POSITIVE_INFINITY;
  }
  // return length of shortest path from s to v
  public double distTo(int v) {
    return distTo[v];
  }
  // return view of shortest path from s to v, null if no such path
  public Iterable<DirectedEdge> pathTo(int v) {
    if (!hasPathTo(v)) return null;
    Stack<DirectedEdge> path = new Stack<>();
    for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {
      path.push(e);
    }
    return path;
  }
  // check optimality conditions: either
  // (i) there exists a negative cycle reacheable from s
  //     or
  // (ii)  for all edges e = v->w:            distTo[w] <= distTo[v] + e.weight()
  // (ii') for all edges e = v->w on the SPT: distTo[w] == distTo[v] + e.weight()
  private boolean check(EdgeWeightedDigraph G, int s) {
    // has a negative cycle
    if (hasNegativeCycle()) {
      double weight = 0.0;
      for (DirectedEdge e : negativeCycle()) {
        weight += e.weight();
      }
      if (weight >= 0.0) {
        System.err.println("error: weight of negative cycle = " + weight);
        return false;
      }
    }
    // no negative cycle reachable from source
    else {
      // check that distTo[v] and edgeTo[v] are consistent
      if (distTo[s] != 0.0 || edgeTo[s] != null) {
        System.err.println("distanceTo[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;
        }
      }
    }
    StdOut.println("Satisfies optimality conditions");
    StdOut.println();
    return true;
  }
  public static void main(String[] args) {
    In in = new In(args[0]);
    int s = Integer.parseInt(args[1]);
    EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
    BellmanFordSP sp = new BellmanFordSP(G, s);
    // print negative cycle
    if (sp.hasNegativeCycle()) {
      for (DirectedEdge e : sp.negativeCycle())
        StdOut.println(e);
    }
    // print shortest paths
    else {
      for (int v = 0; v < G.V(); v++) {
        if (sp.hasPathTo(v)) {
          StdOut.format("%d to %d (%5.2f)  ", s, v, sp.distTo(v));
          for (DirectedEdge e : sp.pathTo(v)) {
            StdOut.print(e + "   ");
          }
          StdOut.println();
        }
        else {
          StdOut.format("%d to %d           no path\n", s, v);
        }
      }
    }
  }
}
 |