{"record":{"id":"b910d7a66b837865","repo":"TheAlgorithms/Java","slug":"maze-must-be-a-square-n-x-n-matrix","errorCode":null,"errorMessage":"Maze must be a square (n x n) matrix.","messagePattern":"Maze must be a square \\(n x n\\) matrix\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/backtracking/RatInAMaze.java","lineNumber":51,"sourceCode":"    private RatInAMaze() {\n    }\n\n    /**\n     * Finds all paths from the top-left to the bottom-right of the given maze.\n     *\n     * @param maze an {@code n x n} binary matrix where {@code 1} = open, {@code 0} = blocked\n     * @return a sorted list of all valid path strings using directions D, L, R, U;\n     *         an empty list if no path exists\n     * @throws IllegalArgumentException if the maze is null, empty, or not square\n     */\n    public static List<String> findPaths(final int[][] maze) {\n        if (maze == null || maze.length == 0) {\n            throw new IllegalArgumentException(\"Maze must not be null or empty.\");\n        }\n        int n = maze.length;\n        for (int[] row : maze) {\n            if (row.length != n) {\n                throw new IllegalArgumentException(\"Maze must be a square (n x n) matrix.\");\n            }\n        }\n        List<String> results = new ArrayList<>();\n        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) {\n            return results;\n        }\n        boolean[][] visited = new boolean[n][n];\n        solve(maze, 0, 0, n, \"\", visited, results);\n        return results;\n    }\n\n    /**\n     * Recursive backtracking helper that explores all four directions.\n     *\n     * @param maze    the binary maze\n     * @param row     current row position\n     * @param col     current column position\n     * @param n       maze dimension","sourceCodeStart":33,"sourceCodeEnd":69,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/backtracking/RatInAMaze.java#L33-L69","documentation":"Thrown by RatInAMaze.findPaths(maze) when any row's length differs from the number of rows, i.e. the matrix is not square. The pathfinding algorithm assumes an n x n grid (it indexes maze[n-1][n-1] and uses n for both dimensions), so a ragged or rectangular matrix breaks the coordinate model.","triggerScenarios":"Calling `findPaths` with a matrix where some `row.length != maze.length`, e.g. a 2x3 matrix `{{1,0,1},{1,1,1}}` or a ragged array `{{1,1},{1}}`.","commonSituations":"Loading a maze from a text file with inconsistent row lengths; trimming whitespace that changed row widths; transposing or reshaping a matrix incorrectly.","solutions":["Ensure every row has exactly the same length as the number of rows (n x n).","Validate the matrix shape when parsing: pad short rows or reject the input with a clear message.","If a rectangular (non-square) maze is intended, adapt the algorithm rather than passing it here."],"exampleFix":"// before\nint[][] maze = {{1,0,1},{1,1,1}};  // 2x3 -> throws\nRatInAMaze.findPaths(maze);\n\n// after\nint[][] maze = {{1,0},{1,1}};  // 2x2 square\nRatInAMaze.findPaths(maze);","handlingStrategy":"type-guard","validationCode":"public static boolean isSquare(int[][] m) {\n    if (m == null || m.length == 0) return false;\n    int n = m.length;\n    for (int[] row : m) if (row == null || row.length != n) return false;\n    return true;\n}\n// usage\nif (!isSquare(maze)) throw new IllegalArgumentException(\"maze must be n x n\");\nRatInAMaze.findPaths(maze);","typeGuard":"public static boolean isSquare(int[][] m) {\n    if (m == null || m.length == 0) return false;\n    int n = m.length;\n    for (int[] row : m) if (row == null || row.length != n) return false;\n    return true;\n}","tryCatchPattern":"try {\n    return RatInAMaze.findPaths(maze);\n} catch (IllegalArgumentException e) {\n    log.error(\"maze not square: {}\", e.getMessage());\n    return Collections.emptyList();\n}","preventionTips":["Validate row lengths when parsing the maze file.","Pad or reject ragged rows at load time.","Unit-test the loader with malformed input."],"tags":["backtracking","matrix","shape-validation","argument-validation","illegalargumentexception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}