算法 6.4节 Ford-Fulkerson最大流算法

import edu.princeton.cs.algs4.Queue;

public class FordFulkerson {
    private double value;
    private boolean[] marked;
    private FlowEdge[] edgeTo;

    public FordFulkerson(FlowNetwork G, int s, int t) {
        while (hasPath(G, s, t)) {
            double bottle = Double.POSITIVE_INFINITY;
            for (int v = t;v != s; v = edgeTo[v].other(v)) {
                bottle = Math.min(bottle, edgeTo[v].residualCapacityTo(v));
            }
            for (int v = t;v != s; v = edgeTo[v].other(v)){
                edgeTo[v].addResidualCapacityTo(v,bottle);
            }
            value += bottle;
        }
    }

    private boolean hasPath(FlowNetwork G, int s, int t) {
        marked = new boolean[G.V()];
        edgeTo = new FlowEdge[G.V()];
        Queue<Integer> queue = new Queue<Integer>();

        marked[s] =true;
        queue.enqueue(s);
        while (!queue.isEmpty()) {
            int v = queue.dequeue();
            for (FlowEdge e : G.adj(v)) {
                int w = e.other(v);
                if (e.residualCapacityTo(w) > 0 && !marked[w]) {
                    edgeTo[w] = e;
                    marked[w] = true;
                    queue.enqueue(w);
                }
            }
        }
        return marked[t];
    }
}
点赞