{"record":{"id":"e8bb798d9b99ec08","repo":"TheAlgorithms/Java","slug":"weights-matrix-must-be-square","errorCode":null,"errorMessage":"Weights matrix must be square","messagePattern":"Weights matrix must be square","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/graph/YensKShortestPaths.java","lineNumber":119,"sourceCode":"            shortestPaths.add(candidates.poll());\n        }\n\n        // Map to list of node indices for output\n        List<List<Integer>> result = new ArrayList<>(shortestPaths.size());\n        for (Path p : shortestPaths) {\n            result.add(new ArrayList<>(p.nodes));\n        }\n        return result;\n    }\n\n    private static void validate(int[][] weights, int src, int dst, int k) {\n        if (weights == null || weights.length == 0) {\n            throw new IllegalArgumentException(\"Weights matrix must not be null or empty\");\n        }\n        int n = weights.length;\n        for (int i = 0; i < n; i++) {\n            if (weights[i] == null || weights[i].length != n) {\n                throw new IllegalArgumentException(\"Weights matrix must be square\");\n            }\n            for (int j = 0; j < n; j++) {\n                int val = weights[i][j];\n                if (val < NO_EDGE) {\n                    throw new IllegalArgumentException(\"Weights must be -1 (no edge) or >= 0\");\n                }\n            }\n        }\n        if (src < 0 || dst < 0 || src >= n || dst >= n) {\n            throw new IllegalArgumentException(\"Invalid src/dst indices\");\n        }\n        if (k < 1) {\n            throw new IllegalArgumentException(\"k must be >= 1\");\n        }\n    }\n\n    private static boolean startsWith(List<Integer> list, List<Integer> prefix) {\n        if (prefix.size() > list.size()) {","sourceCodeStart":101,"sourceCodeEnd":137,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java#L101-L137","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Allocate with new int[n][n] and initialize all cells to -1 (NO_EDGE), then fill in actual edges.","Pre-validate: for (int[] r : weights) if (r == null || r.length != n) throw ....","When building from an edge list, loop i and j over [0,n) to guarantee full coverage."],"exampleFix":"// before\nint[][] w = new int[n][]; // rows null\nfor (Edge e : edges) w[e.u][e.v] = e.weight;\n\n// after\nint[][] w = new int[n][n];\nArrays.stream(w).forEach(r -> Arrays.fill(r, -1)); // -1 = no edge\nfor (Edge e : edges) w[e.u][e.v] = e.weight;","handlingStrategy":"validation","validationCode":"int n = weights.length;\nfor (int[] row : weights) {\n    if (row == null || row.length != n) {\n        throw new IllegalArgumentException(\"weights matrix must be square\");\n    }\n}\nYensKShortestPaths.kShortestPaths(weights, src, dst, k);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Allocate with new int[n][n] and initialize all cells to -1 before setting real edges.","Avoid new int[n][] (partial allocation) for matrices that must be square.","Validate matrix shape once at the boundary where untrusted data enters."],"tags":["graph","validation","matrix","null-check","ragged-array","yens"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}