TheAlgorithms/Java · error · IllegalArgumentException
Capacity matrix must be square
Error message
Capacity matrix must be square
What it means
PushRelabel.validate throws this IllegalArgumentException when any row is null or its length differs from n (the matrix dimension). The push-relabel algorithm indexes capacity[u][v] symmetrically, requiring a square n×n matrix.
Source
Thrown at src/main/java/com/thealgorithms/graph/PushRelabel.java:150
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
- Allocate new int[n][n] and fill capacity[u][v] per edge.
- Verify all rows are non-null and length n.
- Replace null rows with new int[n] before calling.
Example fix
// before int[][] cap = new int[n][]; // uninitialized rows // after int[][] cap = new int[n][n];
Defensive patterns
Strategy: validation
Validate before calling
for (int[] row : capacity) {
if (row == null || row.length != capacity.length) {
throw new IllegalArgumentException("Non-square matrix");
}
} Type guard
boolean isSquare(int[][] cap) {
if (cap == null) return false;
for (int[] row : cap) if (row == null || row.length != cap.length) return false;
return true;
} Prevention
- Allocate new int[n][n] directly.
- Never leave rows uninitialized.
- Reuse a shared square-matrix validator.
When it happens
Trigger: Passing a ragged array, a non-square rectangular matrix, or a matrix with a null row.
Common situations: Allocating new int[n][] and forgetting to initialize rows. Mixing edge-list-derived sizing with vertex-count sizing. Null row after partial fill.
Related errors
- Capacity matrix must be square
- Capacity matrix must not be null or empty
- 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/53e5a756ad470a2c.
Report an issue: GitHub.