Skip to content

Commit 883a050

Browse files
SamXop123alxkm
andauthored
Added Dinic’s Max Flow algorithm with tests [Graphs] (TheAlgorithms#6762)
* Add Dinics max flow algorithm with tests and index update * Docs: add Dinic reference link and apply clang-format * Fix: Checkstyle violations in Dinic and tests * style: apply clang-format to Dinic and tests --------- Co-authored-by: a <alexanderklmn@gmail.com>
1 parent 387ecef commit 883a050

File tree

3 files changed

+191
-0
lines changed

3 files changed

+191
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,7 @@
353353
- 📄 [PredecessorConstrainedDfs](src/main/java/com/thealgorithms/graph/PredecessorConstrainedDfs.java)
354354
- 📄 [StronglyConnectedComponentOptimized](src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java)
355355
- 📄 [TravelingSalesman](src/main/java/com/thealgorithms/graph/TravelingSalesman.java)
356+
- 📄 [Dinic](src/main/java/com/thealgorithms/graph/Dinic.java)
356357
- 📁 **greedyalgorithms**
357358
- 📄 [ActivitySelection](src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java)
358359
- 📄 [BandwidthAllocation](src/main/java/com/thealgorithms/greedyalgorithms/BandwidthAllocation.java)
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Arrays;
5+
import java.util.Queue;
6+
7+
/**
8+
* Dinic's algorithm for computing maximum flow in a directed graph.
9+
*
10+
* <p>Time complexity: O(E * V^2) in the worst case, but typically faster in practice
11+
* and near O(E * sqrt(V)) for unit networks.</p>
12+
*
13+
* <p>The graph is represented using a capacity matrix where capacity[u][v] is the
14+
* capacity of the directed edge u -> v. Capacities must be non-negative.
15+
* The algorithm builds level graphs using BFS and finds blocking flows using DFS
16+
* with current-edge optimization.</p>
17+
*
18+
* <p>This implementation mirrors the API and validation style of
19+
* {@link EdmondsKarp#maxFlow(int[][], int, int)} for consistency.</p>
20+
*
21+
* @see <a href="https://en.wikipedia.org/wiki/Dinic%27s_algorithm">Wikipedia: Dinic's algorithm</a>
22+
*/
23+
public final class Dinic {
24+
private Dinic() {
25+
}
26+
27+
/**
28+
* Computes the maximum flow from source to sink using Dinic's algorithm.
29+
*
30+
* @param capacity square capacity matrix (n x n); entries must be >= 0
31+
* @param source source vertex index in [0, n)
32+
* @param sink sink vertex index in [0, n)
33+
* @return the maximum flow value
34+
* @throws IllegalArgumentException if the input matrix is null/non-square/has negatives or
35+
* indices invalid
36+
*/
37+
public static int maxFlow(int[][] capacity, int source, int sink) {
38+
if (capacity == null || capacity.length == 0) {
39+
throw new IllegalArgumentException("Capacity matrix must not be null or empty");
40+
}
41+
final int n = capacity.length;
42+
for (int i = 0; i < n; i++) {
43+
if (capacity[i] == null || capacity[i].length != n) {
44+
throw new IllegalArgumentException("Capacity matrix must be square");
45+
}
46+
for (int j = 0; j < n; j++) {
47+
if (capacity[i][j] < 0) {
48+
throw new IllegalArgumentException("Capacities must be non-negative");
49+
}
50+
}
51+
}
52+
if (source < 0 || sink < 0 || source >= n || sink >= n) {
53+
throw new IllegalArgumentException("Source and sink must be valid vertex indices");
54+
}
55+
if (source == sink) {
56+
return 0;
57+
}
58+
59+
// residual capacities
60+
int[][] residual = new int[n][n];
61+
for (int i = 0; i < n; i++) {
62+
residual[i] = Arrays.copyOf(capacity[i], n);
63+
}
64+
65+
int[] level = new int[n];
66+
int flow = 0;
67+
while (bfsBuildLevelGraph(residual, source, sink, level)) {
68+
int[] next = new int[n]; // current-edge optimization
69+
int pushed;
70+
do {
71+
pushed = dfsBlocking(residual, level, next, source, sink, Integer.MAX_VALUE);
72+
flow += pushed;
73+
} while (pushed > 0);
74+
}
75+
return flow;
76+
}
77+
78+
private static boolean bfsBuildLevelGraph(int[][] residual, int source, int sink, int[] level) {
79+
Arrays.fill(level, -1);
80+
level[source] = 0;
81+
Queue<Integer> q = new ArrayDeque<>();
82+
q.add(source);
83+
while (!q.isEmpty()) {
84+
int u = q.poll();
85+
for (int v = 0; v < residual.length; v++) {
86+
if (residual[u][v] > 0 && level[v] == -1) {
87+
level[v] = level[u] + 1;
88+
if (v == sink) {
89+
return true;
90+
}
91+
q.add(v);
92+
}
93+
}
94+
}
95+
return level[sink] != -1;
96+
}
97+
98+
private static int dfsBlocking(int[][] residual, int[] level, int[] next, int u, int sink, int f) {
99+
if (u == sink) {
100+
return f;
101+
}
102+
final int n = residual.length;
103+
for (int v = next[u]; v < n; v++, next[u] = v) {
104+
if (residual[u][v] <= 0) {
105+
continue;
106+
}
107+
if (level[v] != level[u] + 1) {
108+
continue;
109+
}
110+
int pushed = dfsBlocking(residual, level, next, v, sink, Math.min(f, residual[u][v]));
111+
if (pushed > 0) {
112+
residual[u][v] -= pushed;
113+
residual[v][u] += pushed;
114+
return pushed;
115+
}
116+
}
117+
return 0;
118+
}
119+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.thealgorithms.graph;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.DisplayName;
7+
import org.junit.jupiter.api.Test;
8+
9+
class DinicTest {
10+
@Test
11+
@DisplayName("Classic CLRS network yields max flow 23 (Dinic)")
12+
void clrsExample() {
13+
int[][] capacity = {{0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}};
14+
int maxFlow = Dinic.maxFlow(capacity, 0, 5);
15+
assertEquals(23, maxFlow);
16+
}
17+
18+
@Test
19+
@DisplayName("Disconnected network has zero flow (Dinic)")
20+
void disconnectedGraph() {
21+
int[][] capacity = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
22+
int maxFlow = Dinic.maxFlow(capacity, 0, 2);
23+
assertEquals(0, maxFlow);
24+
}
25+
26+
@Test
27+
@DisplayName("Source equals sink returns zero (Dinic)")
28+
void sourceEqualsSink() {
29+
int[][] capacity = {{0, 5}, {0, 0}};
30+
int maxFlow = Dinic.maxFlow(capacity, 0, 0);
31+
assertEquals(0, maxFlow);
32+
}
33+
34+
@Test
35+
@DisplayName("Invalid matrix throws exception (Dinic)")
36+
void invalidMatrix() {
37+
int[][] capacity = {{0, 1}, {1}};
38+
assertThrows(IllegalArgumentException.class, () -> Dinic.maxFlow(capacity, 0, 1));
39+
}
40+
41+
@Test
42+
@DisplayName("Dinic matches Edmonds-Karp on random small graphs")
43+
void parityWithEdmondsKarp() {
44+
java.util.Random rnd = new java.util.Random(42);
45+
for (int n = 3; n <= 7; n++) {
46+
for (int it = 0; it < 25; it++) {
47+
int[][] cap = new int[n][n];
48+
for (int i = 0; i < n; i++) {
49+
for (int j = 0; j < n; j++) {
50+
if (i != j && rnd.nextDouble() < 0.35) {
51+
cap[i][j] = rnd.nextInt(10); // capacities 0..9
52+
}
53+
}
54+
}
55+
int s = 0;
56+
int t = n - 1;
57+
int f1 = Dinic.maxFlow(copyMatrix(cap), s, t);
58+
int f2 = EdmondsKarp.maxFlow(cap, s, t);
59+
assertEquals(f2, f1);
60+
}
61+
}
62+
}
63+
64+
private static int[][] copyMatrix(int[][] a) {
65+
int[][] b = new int[a.length][a.length];
66+
for (int i = 0; i < a.length; i++) {
67+
b[i] = java.util.Arrays.copyOf(a[i], a[i].length);
68+
}
69+
return b;
70+
}
71+
}

0 commit comments

Comments
 (0)