I have some simple Java/JUNG code that creates a directed graph, adds some edges with weights and capacity values, and runs a max flow analysis from the source node to sink node.
If you have: A --- (capacity 2) -----> B ---- (capacity 5)----> C and want to find max flow from A->C, it will be 2.
import edu.uci.ics.jung.algorithms.flows.EdmondsKarpMaxFlow;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import java.util.HashMap;
import java.util.Map;
public class stack {
static int edgeCount = 0;
static class MyNode {
int id;
public MyNode(int id) {
this.id = id;
}
public String toString() {
return "V"+id;
}
}
static class MyLink {
double capacity;
double weight;
int id;
public MyLink(double weight, double capacity) {
this.id = edgeCount++;
this.weight = weight;
this.capacity = capacity;
}
public String toString() {
return "E"+id;
}
}
public static void main(String[] args){
DirectedSparseMultigraph<MyNode, MyLink> g = new DirectedSparseMultigraph<MyNode, MyLink>();
Transformer<MyLink, Double> capTransformer = new Transformer<MyLink, Double>(){
public Double transform(MyLink link) {
return link.capacity;
}
};
Map<MyLink, Double> edgeFlowMap = new HashMap<MyLink, Double>();
// This Factory produces new edges for use by the algorithm
Factory<MyLink> edgeFactory = new Factory<MyLink>() {
public MyLink create() {
return new MyLink(1.0, 1.0);
}
};
// Create some MyNode objects to use as vertices
MyNode n1 = new MyNode(1);
MyNode n2 = new MyNode(2);
MyNode n3 = new MyNode(3);
MyNode n4 = new MyNode(4);
MyNode n5 = new MyNode(5);
MyNode n6 = new MyNode(6);
MyNode n7 = new MyNode(7);
// Add some directed edges along with the vertices to the graph
g.addEdge(new MyLink(2.0, 48),n1, n2, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 58),n2, n3, EdgeType.DIRECTED);
g.addEdge(new MyLink(3.0, 192), n3, n5, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 48), n5, n4, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 20), n6, n1, EdgeType.DIRECTED);
g.addEdge(new MyLink(8, 24), n7, n4, EdgeType.DIRECTED);
System.out.println("RUNNING EDMONDS KARP MAX FLOW FOR SOURCE " + n1.toString() + " TO SINK " + n2.toString());
EdmondsKarpMaxFlow<MyNode, MyLink> edk = new EdmondsKarpMaxFlow(g, n1, n2, capTransformer, edgeFlowMap, edgeFactory);
edk.evaluate();
System.out.println("The max flow is: " + edk.getMaxFlow());
}
}
Running this will output:
RUNNING EDMONDS KARP MAX FLOW FOR SOURCE V1 TO SINK V2 The max flow is: 48
How can write an algorithm to make it run on every possible pair of source and sinks so I can see max flow of all paths in the graph? Completely new to this stuff so anything helps!
Just run the algorithm for every pair of nodes. There is no known algorithm that is more efficient for directed graphs: All pair Maximum Flow