TheAlgorithms/Java · error · IllegalArgumentException

Cost matrix must have at least 1 column

Error message

Cost matrix must have at least 1 column

What it means

HungarianAlgorithm.validate throws this IllegalArgumentException when the cost matrix has rows but the first row has zero columns (c == 0). It guards against a degenerate matrix that has no columns to assign workers to.

Source

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

        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. Ensure each row has at least one column before calling.
  2. Treat an empty task set as a no-op assignment upstream.
  3. Validate column count > 0 during matrix construction.

Example fix

// before
int[][] cost = workers.stream().map(w -> new int[0]).toArray(int[][]::new);

// after
if (tasks.isEmpty()) return new int[0];
int[][] cost = buildCostMatrix(workers, tasks); // guarantees cols >= 1
Defensive patterns

Strategy: validation

Validate before calling

if (cost.length > 0 && (cost[0] == null || cost[0].length == 0)) {
    throw new IllegalArgumentException("Cost matrix needs at least 1 column");
}

Type guard

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

Prevention

When it happens

Trigger: Passing a matrix like new int[3][] where each row is empty, or new int[][]{{}}.

Common situations: Building rows as new int[0] when no tasks are configured. A column count derived from an empty task list. Matrix transposition logic that dropped columns.

Related errors


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