TheAlgorithms/Java · error · IllegalArgumentException

Maze must be a square (n x n) matrix.

Error message

Maze must be a square (n x n) matrix.

What it means

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.

Source

Thrown at src/main/java/com/thealgorithms/backtracking/RatInAMaze.java:51

    private RatInAMaze() {
    }

    /**
     * Finds all paths from the top-left to the bottom-right of the given maze.
     *
     * @param maze an {@code n x n} binary matrix where {@code 1} = open, {@code 0} = blocked
     * @return a sorted list of all valid path strings using directions D, L, R, U;
     *         an empty list if no path exists
     * @throws IllegalArgumentException if the maze is null, empty, or not square
     */
    public static List<String> findPaths(final int[][] maze) {
        if (maze == null || maze.length == 0) {
            throw new IllegalArgumentException("Maze must not be null or empty.");
        }
        int n = maze.length;
        for (int[] row : maze) {
            if (row.length != n) {
                throw new IllegalArgumentException("Maze must be a square (n x n) matrix.");
            }
        }
        List<String> results = new ArrayList<>();
        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) {
            return results;
        }
        boolean[][] visited = new boolean[n][n];
        solve(maze, 0, 0, n, "", visited, results);
        return results;
    }

    /**
     * Recursive backtracking helper that explores all four directions.
     *
     * @param maze    the binary maze
     * @param row     current row position
     * @param col     current column position
     * @param n       maze dimension

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure every row has exactly the same length as the number of rows (n x n).
  2. Validate the matrix shape when parsing: pad short rows or reject the input with a clear message.
  3. If a rectangular (non-square) maze is intended, adapt the algorithm rather than passing it here.

Example fix

// before
int[][] maze = {{1,0,1},{1,1,1}};  // 2x3 -> throws
RatInAMaze.findPaths(maze);

// after
int[][] maze = {{1,0},{1,1}};  // 2x2 square
RatInAMaze.findPaths(maze);
Defensive patterns

Strategy: type-guard

Validate before calling

public static boolean isSquare(int[][] m) {
    if (m == null || m.length == 0) return false;
    int n = m.length;
    for (int[] row : m) if (row == null || row.length != n) return false;
    return true;
}
// usage
if (!isSquare(maze)) throw new IllegalArgumentException("maze must be n x n");
RatInAMaze.findPaths(maze);

Type guard

public static boolean isSquare(int[][] m) {
    if (m == null || m.length == 0) return false;
    int n = m.length;
    for (int[] row : m) if (row == null || row.length != n) return false;
    return true;
}

Try / catch

try {
    return RatInAMaze.findPaths(maze);
} catch (IllegalArgumentException e) {
    log.error("maze not square: {}", e.getMessage());
    return Collections.emptyList();
}

Prevention

When it happens

Trigger: 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}}`.

Common situations: Loading a maze from a text file with inconsistent row lengths; trimming whitespace that changed row widths; transposing or reshaping a matrix incorrectly.

Related errors


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