TheAlgorithms/Java · error · IllegalArgumentException
Cost matrix must be rectangular with equal row lengths
Error message
Cost matrix must be rectangular with equal row lengths
What it means
HungarianAlgorithm.validate throws this IllegalArgumentException when any row is null or its length differs from the first row's length c. Unlike the flow algorithms, the Hungarian algorithm accepts rectangular (non-square) matrices but requires consistent column counts across all rows.
Source
Thrown at src/main/java/com/thealgorithms/graph/HungarianAlgorithm.java:141
if (j >= 0 && j < cols) {
assignment[i] = j;
total += cost[i][j];
}
}
return new Result(assignment, total);
}
private static void validate(int[][] cost) {
if (cost == null || cost.length == 0) {
throw new IllegalArgumentException("Cost matrix must not be null or empty");
}
int c = cost[0].length;
if (c == 0) {
throw new IllegalArgumentException("Cost matrix must have at least 1 column");
}
for (int i = 0; i < cost.length; i++) {
if (cost[i] == null || cost[i].length != c) {
throw new IllegalArgumentException("Cost matrix must be rectangular with equal row lengths");
}
for (int j = 0; j < c; j++) {
if (cost[i][j] < 0) {
throw new IllegalArgumentException("Costs must be non-negative");
}
}
}
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Pad all rows to the same column count (max across workers) before calling.
- Ensure every row is non-null and of equal length.
- Validate row lengths against the first row during construction.
Example fix
// before
int[][] cost = { {1,2}, {3} }; // ragged
// after
int[][] cost = { {1,2}, {3,0} }; // pad missing with large/zero cost Defensive patterns
Strategy: validation
Validate before calling
int cols = cost[0].length;
for (int[] row : cost) {
if (row == null || row.length != cols) {
throw new IllegalArgumentException("Ragged cost matrix");
}
} Type guard
boolean isRectangular(int[][] cost) {
if (cost == null || cost.length == 0) return false;
int c = cost[0].length;
for (int[] row : cost) if (row == null || row.length != c) return false;
return true;
} Prevention
- Pad all rows to the same column count.
- Validate row lengths against the first row during construction.
- Use a builder that enforces consistent dimensions.
When it happens
Trigger: Passing a ragged array where rows have differing lengths, or a matrix with a null row.
Common situations: Appending tasks per worker without aligning column counts. A null row from incomplete initialization. Mixing data sources with different task counts.
Related errors
- Cost matrix must have at least 1 column
- Capacity matrix must be square
- Capacity matrix must be square
- Cost matrix must not be null or empty
- Costs must be non-negative
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/83b04f8f73c3fa09.
Report an issue: GitHub.