TheAlgorithms/Java · error · IllegalArgumentException

Cost matrix must not be null or empty

Error message

Cost matrix must not be null or empty

What it means

HungarianAlgorithm.validate throws this IllegalArgumentException when the cost matrix is null or has zero rows. It is the first guard in the validator that protects the assignment algorithm's row/column bookkeeping.

Source

Thrown at src/main/java/com/thealgorithms/graph/HungarianAlgorithm.java:133

        }

        // Build assignment for original rows only, ignore padded rows
        int[] assignment = new int[rows];
        Arrays.fill(assignment, -1);
        int total = 0;
        for (int i = 0; i < rows; i++) {
            int j = matchColForRow[i];
            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

  1. Handle null/empty as a special case (return an empty assignment) before calling.
  2. Ensure at least one worker and one task exist before constructing the matrix.
  3. Guard the upstream data source that produces the cost matrix.

Example fix

// before
HungarianAlgorithm.Result r = HungarianAlgorithm.solve(cost);

// after
if (cost == null || cost.length == 0) {
    return new int[0];
}
HungarianAlgorithm.Result r = HungarianAlgorithm.solve(cost);
Defensive patterns

Strategy: validation

Validate before calling

if (cost == null || cost.length == 0) {
    return new int[0]; // no workers
}

Type guard

boolean hasRows(int[][] cost) { return cost != null && cost.length > 0; }

Prevention

When it happens

Trigger: Calling the Hungarian algorithm with null or an empty int[][] cost matrix.

Common situations: An empty assignment problem (no workers or no tasks). Matrix not built yet due to an earlier exception. Deserialization returning null.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/b4bc55abc3998a4b. Report an issue: GitHub.