TheAlgorithms/Java · error · IllegalArgumentException
Capacity matrix must not be null or empty
Error message
Capacity matrix must not be null or empty
What it means
PushRelabel.validate throws this IllegalArgumentException when the capacity matrix is null or has zero rows. It is the first guard before the push-relabel maximum flow computation, ensuring the matrix exists.
Source
Thrown at src/main/java/com/thealgorithms/graph/PushRelabel.java:145
}
}
private static void relabel(int u, int[][] residual, int[] height) {
final int n = residual.length;
int minHeight = Integer.MAX_VALUE;
for (int v = 0; v < n; v++) {
if (residual[u][v] > 0) {
minHeight = Math.min(minHeight, height[v]);
}
}
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
- Null/empty-check the matrix and return 0 flow before calling.
- Ensure the graph has at least one vertex.
- Log upstream when the loader produces an empty matrix.
Example fix
// before int flow = PushRelabel.maxFlow(cap, s, t); // after if (cap == null || cap.length == 0) return 0; int flow = PushRelabel.maxFlow(cap, s, t);
Defensive patterns
Strategy: validation
Validate before calling
if (capacity == null || capacity.length == 0) {
return 0;
} Type guard
boolean hasMatrix(int[][] cap) { return cap != null && cap.length > 0; } Prevention
- Return 0 flow for empty graphs at the caller.
- Ensure graph construction yields at least one vertex.
- Log empty matrices to catch upstream bugs.
When it happens
Trigger: Calling PushRelabel with a null capacity array or new int[0][].
Common situations: Empty graph parsed from input. Matrix uninitialized after a failed build step. Null returned from a graph loader.
Related errors
- Capacity matrix must not be null or empty
- Capacity matrix must be square
- Capacities must be non-negative
- 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/100657a89a478029.
Report an issue: GitHub.