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
GomoryHuTree.validateCapacityMatrix throws this IllegalArgumentException when the capacity matrix passed to the public API is null or has zero rows. It is the first check in the private validator invoked before any tree construction.
Source
Thrown at src/main/java/com/thealgorithms/graph/GomoryHuTree.java:56
for (int v = 0; v < n; v++) {
if (v != s && parent[v] == t && res.reachable[v]) {
parent[v] = s;
}
}
if (t != 0 && res.reachable[parent[t]]) {
parent[s] = parent[t];
parent[t] = s;
weight[s] = weight[t];
weight[t] = f;
}
}
return new int[][] {parent, weight};
}
private static void validateCapacityMatrix(int[][] cap) {
if (cap == null || cap.length == 0) {
throw new IllegalArgumentException("Capacity matrix must not be null or empty");
}
final int n = cap.length;
for (int i = 0; i < n; i++) {
if (cap[i] == null || cap[i].length != n) {
throw new IllegalArgumentException("Capacity matrix must be square");
}
for (int j = 0; j < n; j++) {
if (cap[i][j] < 0) {
throw new IllegalArgumentException("Capacities must be non-negative");
}
}
}
}
private static final class MaxFlowResult {
final int flow;
final boolean[] reachable;
MaxFlowResult(int flow, boolean[] reachable) {View on GitHub (pinned to fdfb9a395b)
Solutions
- Null/empty-check the matrix before invoking the Gomory-Hu method and return an empty result.
- Ensure the graph build step produces at least one vertex.
- Log when the matrix comes back empty from the loader to catch upstream bugs.
Example fix
// before
int[][] tree = GomoryHuTree.build(cap); // cap may be null
// after
if (cap == null || cap.length == 0) {
return new int[0][];
}
int[][] tree = GomoryHuTree.build(cap); Defensive patterns
Strategy: validation
Validate before calling
if (cap == null || cap.length == 0) {
return new int[0][]; // empty tree
} Type guard
boolean hasMatrix(int[][] cap) { return cap != null && cap.length > 0; } Prevention
- Handle empty graphs at the caller before invoking Gomory-Hu.
- Ensure graph loaders return a non-null matrix.
- Log empty-matrix cases to catch upstream issues.
When it happens
Trigger: Calling the Gomory-Hu tree constructor/method with a null capacity array or an empty int[][] (length 0).
Common situations: Graph parsed from input that yielded no vertices. Matrix left uninitialized after a failed load. Guard removed during a refactor assuming upstream always provides data.
Related errors
- Capacity matrix must not be null or empty
- Capacity matrix must be square
- Capacities must be non-negative
- Cost matrix must not be null or empty
- successors must not be null
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/f54232c2b0340e21.
Report an issue: GitHub.