TheAlgorithms/Java · error · IllegalArgumentException
Capacities must be non-negative
Error message
Capacities must be non-negative
What it means
PushRelabel.validate throws this IllegalArgumentException when any capacity cell is negative. Push-relabel's preflow and relabel operations assume non-negative capacities; negative values break the excess invariant and can produce incorrect flow values.
Source
Thrown at src/main/java/com/thealgorithms/graph/PushRelabel.java:154
}
}
if (minHeight < Integer.MAX_VALUE) {
height[u] = minHeight + 1;
}
}
private static void validate(int[][] capacity, int source, int sink) {
if (capacity == null || capacity.length == 0) {
throw new IllegalArgumentException("Capacity matrix must not be null or empty");
}
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");
}
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Use 0 for no-edge representation.
- Clamp parsed values with Math.max(0, val).
- Unit-test the matrix for non-negativity before calling.
Example fix
// before cap[u][v] = hasEdge ? w : -1; // after cap[u][v] = hasEdge ? w : 0;
Defensive patterns
Strategy: validation
Validate before calling
for (int i = 0; i < capacity.length; i++)
for (int j = 0; j < capacity[i].length; j++)
if (capacity[i][j] < 0) capacity[i][j] = 0; Type guard
boolean allNonNegative(int[][] cap) {
for (int[] row : cap) for (int v : row) if (v < 0) return false;
return true;
} Prevention
- Use 0 for no-edge.
- Clamp parsed values with Math.max(0, val).
- Avoid in-place residual mutation before validation.
When it happens
Trigger: Passing a matrix with any cell < 0, including -1 sentinels for 'no edge'.
Common situations: Using -1 for no-edge. Signed weights not clamped. Buggy in-place residual mutation before calling validate.
Related errors
- Capacities must be non-negative
- Capacity matrix must not be null or empty
- Capacity matrix must be square
- Source and sink must be valid vertex indices
- Source and sink must be valid vertex indices
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/f5becd93569f4928.
Report an issue: GitHub.