TheAlgorithms/Java · error · IllegalArgumentException
Capacities must be non-negative
Error message
Capacities must be non-negative
What it means
Thrown by Dinic.maxFlow when any capacity[i][j] < 0. Flow capacities are non-negative by definition; negative values break the residual-graph invariants. Message: 'Capacities must be non-negative'.
Source
Thrown at src/main/java/com/thealgorithms/graph/Dinic.java:48
* @param capacity square capacity matrix (n x n); entries must be >= 0
* @param source source vertex index in [0, n)
* @param sink sink vertex index in [0, n)
* @return the maximum flow value
* @throws IllegalArgumentException if the input matrix is null/non-square/has negatives or
* indices invalid
*/
public static int maxFlow(int[][] capacity, int source, int sink) {
if (capacity == null || capacity.length == 0) {
throw new IllegalArgumentException("Capacity matrix must not be null or empty");
}
final int n = capacity.length;
for (int i = 0; i < n; i++) {
if (capacity[i] == null || capacity[i].length != n) {
throw new IllegalArgumentException("Capacity matrix must be square");
}
for (int j = 0; j < n; j++) {
if (capacity[i][j] < 0) {
throw new IllegalArgumentException("Capacities must be non-negative");
}
}
}
if (source < 0 || sink < 0 || source >= n || sink >= n) {
throw new IllegalArgumentException("Source and sink must be valid vertex indices");
}
if (source == sink) {
return 0;
}
// residual capacities
int[][] residual = new int[n][n];
for (int i = 0; i < n; i++) {
residual[i] = Arrays.copyOf(capacity[i], n);
}
int[] level = new int[n];
int flow = 0;View on GitHub (pinned to fdfb9a395b)
Solutions
- Use 0 to represent 'no edge' between two vertices, never a negative sentinel.
- Validate every entry >= 0 at the boundary.
- Sanitize parsed numeric input to reject negatives.
Example fix
// before cap[0][1] = -1; // intended 'no edge' // after cap[0][1] = 0; // no edge
Defensive patterns
Strategy: validation
Validate before calling
for (int[] row : capacity) {
for (int c : row) {
if (c < 0) throw new IllegalArgumentException("negative capacity: " + c);
}
} Prevention
- Use 0 (not -1) to mean 'no edge'.
- Validate all entries >= 0 at the build boundary.
- Sanitize parsed numeric input for sign.
When it happens
Trigger: A negative entry in the capacity matrix; using -1 as a 'no edge' sentinel instead of 0; signed parsing of an unsigned source.
Common situations: Sentinel values for 'no edge'; a subtraction that underflowed into a negative capacity; typo'd config with a minus sign.
Related errors
- Capacity matrix must not be null or empty
- Capacity matrix must be square
- Number of vertices must be positive
- Edges list must not be null or empty
- Edge vertex out of range
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/3bd3e0aa7dba60aa.
Report an issue: GitHub.