int [] q = new int[graph.length]; int sizeq = 0; q[sizeq++] = src; for(int i = 0; i < sizeq; i++) { int u = q[i]; for(Edge e : graph[u]) { if(dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1; q[sizeq++] = e.t; } } } return dist[dest] >= 0; } static int dinicDFS(List<Edge>[] graph, int [] ptr, int [] dist,int dest,int u, int f) { if( u== dest) return f; for(;ptr[u] < graph[u].size();++ptr[u]) { Edge e = graph[u].get(ptr[u]); if(dist[e.t] == dist[u] + 1 && e.f < e.cap) { int df = dinicDFS(graph, ptr,dist,dest, e.t, Math.min(f, e.cap - e.f) ); if(df > 0) { e.f += df; graph[e.t].get(e.rev).f -= df; return df; } } } return 0; } public static int maxFlow(List<Edge>[] graph, int src, int dest) { int flow = 0;
int [] dist = new int[graph.length]; while(dinicBFS(graph, src, dest, dist)) { int [] ptr = new int[graph.length]; while(true) { int df = dinicDFS(graph,ptr, dist, dest, src, Integer.MAX_VALUE); if( df == 0) break; flow += df; } } return flow; } static int RandomIntegers(int min,int max) { Random r = new Random(); return r.nextInt((max - min) + 1) + min; } //Driver program with an example public static void main(String[] args) { List<Edge>[] g =createGraph(12); int [] nodes = new int[12];//this refers to nodes inclusive //of source and vertex for(int i = 0; i < 12;i++) { nodes[i] = RandomIntegers(4,12); } for(int i = 1,j = 1; i < 12 && j < 12; i++, j++) { addEdge(g,nodes[i],nodes[j],RandomIntegers(5,20));//allocating //capacities randomly } System.out.println(maxFlow(g,0,11));//returns maxFlow else zero if //none found } }