TheAlgorithms/Java · error · IllegalArgumentException

Weights matrix must be square

Error message

Weights matrix must be square

What it means

YensKShortestPaths requires a square adjacency matrix because it indexes weights[u][v] and weights[i][j] symmetrically and clones the matrix as new int[n][n]. A null row or a row whose length differs from n would break the Dijkstra sub-routine or the defensive copy. The check verifies every row is non-null and exactly n wide.

Source

Thrown at src/main/java/com/thealgorithms/graph/YensKShortestPaths.java:119

            shortestPaths.add(candidates.poll());
        }

        // Map to list of node indices for output
        List<List<Integer>> result = new ArrayList<>(shortestPaths.size());
        for (Path p : shortestPaths) {
            result.add(new ArrayList<>(p.nodes));
        }
        return result;
    }

    private static void validate(int[][] weights, int src, int dst, int k) {
        if (weights == null || weights.length == 0) {
            throw new IllegalArgumentException("Weights matrix must not be null or empty");
        }
        int n = weights.length;
        for (int i = 0; i < n; i++) {
            if (weights[i] == null || weights[i].length != n) {
                throw new IllegalArgumentException("Weights matrix must be square");
            }
            for (int j = 0; j < n; j++) {
                int val = weights[i][j];
                if (val < NO_EDGE) {
                    throw new IllegalArgumentException("Weights must be -1 (no edge) or >= 0");
                }
            }
        }
        if (src < 0 || dst < 0 || src >= n || dst >= n) {
            throw new IllegalArgumentException("Invalid src/dst indices");
        }
        if (k < 1) {
            throw new IllegalArgumentException("k must be >= 1");
        }
    }

    private static boolean startsWith(List<Integer> list, List<Integer> prefix) {
        if (prefix.size() > list.size()) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Allocate with new int[n][n] and initialize all cells to -1 (NO_EDGE), then fill in actual edges.
  2. Pre-validate: for (int[] r : weights) if (r == null || r.length != n) throw ....
  3. When building from an edge list, loop i and j over [0,n) to guarantee full coverage.

Example fix

// before
int[][] w = new int[n][]; // rows null
for (Edge e : edges) w[e.u][e.v] = e.weight;

// after
int[][] w = new int[n][n];
Arrays.stream(w).forEach(r -> Arrays.fill(r, -1)); // -1 = no edge
for (Edge e : edges) w[e.u][e.v] = e.weight;
Defensive patterns

Strategy: validation

Validate before calling

int n = weights.length;
for (int[] row : weights) {
    if (row == null || row.length != n) {
        throw new IllegalArgumentException("weights matrix must be square");
    }
}
YensKShortestPaths.kShortestPaths(weights, src, dst, k);

Prevention

When it happens

Trigger: Passing a ragged matrix (e.g. {{-1,5},{-1}}), a matrix with a null inner array (new int[3][] leaving rows null), or a matrix where some row was truncated during construction.

Common situations: Sparse graph loaded as a list of edge triples and converted to a matrix with only outbound edges filled, a matrix allocated with new int[n][] and not fully initialized, or JSON deserialization producing null rows for vertices with no edges.

Related errors


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