算法 4.4节 Dijkstra算法,拓扑排序算法,bellman-ford算法(暂缺))实现最小路径

// Dijkstra算法
import edu.princeton.cs.algs4.IndexMinPQ;

public class Dijkstra {
    private double[] disTo;
    private Edge[] edgeTo;
    private IndexMinPQ<Double> pq;

    public Dijkstra(EdgeWeightedGraph G, int s) {
        disTo = new double[G.V()];
        edgeTo = new Edge[G.V()];
        pq = new IndexMinPQ<>(G.V());
        for (int v = 0; v< G.V();v++)
            disTo[v] = Double.POSITIVE_INFINITY;
        disTo[s] = 0;
        pq.insert(s, 0.0);

        while (!pq.isEmpty()) {
            relax(G, pq.delMin());
        }
    }

    private void relax(EdgeWeightedGraph G, int s) {
        for (Edge e : G.adj(s)) {
            int w = e.to();
            if (disTo[w] > disTo[s] + e.weight()) {
                disTo[w] = disTo[s] + e.weight();
                edgeTo[w] = e;
                pq.insert(w, disTo[w]);
            }
        }
    }
}
//拓扑排序算法
public class AcyclicSP {
    private double[] disTo;
    private Edge[] edgeTo;

    public AcyclicSP(EdgeWeightedGraph G, int s) {
        disTo = new double[G.V()];
        edgeTo = new Edge[G.V()];
        for (int v = 0; v< G.V();v++)
            disTo[v] = Double.POSITIVE_INFINITY;
        disTo[s] = 0;

        DFSorder order = new DFSorder(G);
        for (int e: order.reversePost()) {
            relax(G, e);
        }
    }

    private void relax(EdgeWeightedGraph G, int s) {
        for (Edge e : G.adj(s)) {
            int w = e.to();
            if (disTo[w] < disTo[s] + e.weight()) {
                disTo[w] = disTo[s] + e.weight();
                edgeTo[w] = e;
            }
        }
    }
}
  • //bellman-ford算法暂缺
点赞