TheAlgorithms/Java · error · IllegalArgumentException

Capacity matrix must be square

Error message

Capacity matrix must be square

What it means

GomoryHuTree.validateCapacityMatrix throws this IllegalArgumentException when any row is null or its length differs from the matrix dimension n. The validator enforces a square n×n matrix because internal max-flow calls index both dimensions symmetrically.

Source

Thrown at src/main/java/com/thealgorithms/graph/GomoryHuTree.java:61

            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) {
            this.flow = flow;
            this.reachable = reachable;
        }
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Allocate with new int[n][n] and fill only [u][v] entries.
  2. Validate every row length equals n before calling.
  3. Replace any null row with new int[n].

Example fix

// before
int[][] cap = new int[n][]; // rows uninitialized

// after
int[][] cap = new int[n][n];
Defensive patterns

Strategy: validation

Validate before calling

for (int[] row : cap) {
    if (row == null || row.length != cap.length) {
        throw new IllegalArgumentException("Non-square capacity 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

When it happens

Trigger: Passing a ragged array, a rectangular (non-square) matrix, or a matrix containing a null row.

Common situations: Allocating rows individually with wrong length. Mixing an adjacency matrix built for n vertices with rows sized for m edges. Null row after partial fill.

Related errors


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