Rat in a Maze

Medium Recursion & Backtracking 2D Matrix Backtracking

Rat in a Maze is a medium recursion & backtracking problem solved with the 2d matrix backtracking pattern. The best approach, optimal (backtracking in alphabetical order), runs in O(3^(n²) · n²) time and O(n²) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (explore every route, then sort) up.

Problem

A rat starts in the top-left cell (0, 0) of an n x n maze and wants to reach the exit in the bottom-right cell (n - 1, n - 1). In maze, a 1 is an open cell the rat can stand on and a 0 is a wall.

In one move the rat steps to a neighbouring cell: U (up), D (down), L (left) or R (right). It can only enter open cells, it cannot leave the grid, and it may not visit any cell twice on the same path.

Write each path as the string of its moves, for example "DRDR". Return all such paths from the start to the exit, sorted in lexicographic (dictionary) order. If the start or the exit is blocked, or the exit cannot be reached, return an empty list.

Examples

Example 1

Input
maze = [[1,1,1,1],[1,0,0,1],[1,1,1,1],[0,0,1,1]]
Output
["DDRRDR", "DDRRRD", "RRRDDD", "RRRDDLDR"]
Why
Two routes go down the left side first and two go along the top first. The route RRRDDLDR steps left once on its way, which is allowed as long as no cell is entered twice. The four strings are listed in sorted order.

Example 2

Input
maze = [[1,1,1],[1,0,1],[1,1,1]]
Output
["DDRR", "RRDD"]
Why
The middle cell is a wall, so the rat goes around it either on the left and bottom (DDRR) or along the top and right (RRDD).

Example 3

Input
maze = [[1,1],[1,0]]
Output
[]
Why
The exit cell is blocked, so no path can end there.

Constraints

  • n == maze.length == maze[i].length
  • 2 <= n <= 5
  • maze[i][j] is 0 (blocked) or 1 (open).

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 35 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (explore every route, then sort)O(3^(n²) · n²)O(n²)
Optimal (backtracking in alphabetical order)O(3^(n²) · n²)O(n²)

1Brute force (explore every route, then sort)

TimeO(3^(n²) · n²)After the first move a route can continue in at most three new directions, and a route visits at most n² cells, so there are at most about 3^(n²) routes. Each step copies a string of length up to n², and sorting P paths costs O(P log P · n²) more. The real counts are far smaller: 8512 routes for a fully open 5 x 5 grid.
SpaceO(n²)The visited grid has n² cells and the recursion goes at most n² calls deep, not counting the output.

Walk from the top-left cell and try every move in every cell, building the direction string as you go. A visited grid remembers which cells the current route already uses. A call that lands outside the grid, on a wall or on a used cell simply returns. A call that reaches the bottom-right cell saves its string. After the search has produced every route, sort the list, because the moves were tried in the order U, D, L, R and the routes come out in that order. Each call builds a new string with path + letter, which copies the route every time.

  1. If the start or the exit is blocked, return an empty list.
  2. explore(r, c, path): return if (r, c) is outside, blocked or visited. If it is the exit, add path and return.
  3. Mark (r, c) visited, call explore for U, D, L and R with the letter added, then unmark (r, c).
  4. Sort the collected paths and return them.
class Solution {
    public List<String> findPath(int[][] maze) {
        int n = maze.length;
        List<String> paths = new ArrayList<>();
        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) return paths;
        boolean[][] visited = new boolean[n][n];
        explore(maze, 0, 0, visited, "", paths);
        Collections.sort(paths);
        return paths;
    }

    private void explore(int[][] maze, int r, int c, boolean[][] visited, String path, List<String> paths) {
        int n = maze.length;
        if (r < 0 || c < 0 || r >= n || c >= n || maze[r][c] == 0 || visited[r][c]) return;
        if (r == n - 1 && c == n - 1) {
            paths.add(path);
            return;
        }
        visited[r][c] = true;
        explore(maze, r - 1, c, visited, path + "U", paths);
        explore(maze, r + 1, c, visited, path + "D", paths);
        explore(maze, r, c - 1, visited, path + "L", paths);
        explore(maze, r, c + 1, visited, path + "R", paths);
        visited[r][c] = false;
    }
}

2Optimal (backtracking in alphabetical order)

TimeO(3^(n²) · n²)The same routes are explored, so the worst case stays exponential. But a move now costs O(1) instead of a string copy, blocked moves are filtered before the call, and the sort disappears; only saving a finished route copies its up to n² letters.
SpaceO(n²)The recursion goes at most n² calls deep and the shared path holds at most n² letters. The maze itself serves as the visited marker, so no extra grid is needed.

Two changes make the search leaner. First, try the moves in alphabetical order: D, L, R, U. A depth-first search lists its routes in the order of the choices it makes at each step, and no route is the beginning of another one (a route stops as soon as it reaches the exit), so the routes come out already sorted and no final sort is needed. Second, keep a single shared StringBuilder: append a letter before going deeper and delete it after coming back, instead of copying the whole string on every move. A cell is marked as used by setting it to 0 while the route passes through it, and set back to 1 on the way out, so the maze is unchanged at the end.

  1. If the start or the exit is blocked, return an empty list.
  2. dfs(r, c): if (r, c) is the exit, add the current path and return.
  3. Set maze[r][c] = 0. For each move in the order D, L, R, U whose target cell is inside the grid and open: append the letter, call dfs on that cell, then remove the letter.
  4. Set maze[r][c] = 1 and return. The collected list is already sorted.
class Solution {
    private static final int[] DR = {1, 0, 0, -1};
    private static final int[] DC = {0, -1, 1, 0};
    private static final char[] DIR = {'D', 'L', 'R', 'U'};

    public List<String> findPath(int[][] maze) {
        int n = maze.length;
        List<String> paths = new ArrayList<>();
        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) return paths;
        dfs(maze, 0, 0, new StringBuilder(), paths);
        return paths;
    }

    private void dfs(int[][] maze, int r, int c, StringBuilder path, List<String> paths) {
        int n = maze.length;
        if (r == n - 1 && c == n - 1) {
            paths.add(path.toString());
            return;
        }
        maze[r][c] = 0;
        for (int d = 0; d < 4; d++) {
            int nr = r + DR[d], nc = c + DC[d];
            if (nr >= 0 && nc >= 0 && nr < n && nc < n && maze[nr][nc] == 1) {
                path.append(DIR[d]);
                dfs(maze, nr, nc, path, paths);
                path.deleteCharAt(path.length() - 1);
            }
        }
        maze[r][c] = 1;
    }
}

Edge cases to test

  • The start cell (0, 0) is blocked: return an empty list
  • The exit cell (n - 1, n - 1) is blocked: return an empty list
  • Both corners are open but walls cut them apart: return an empty list
  • A path may need to move up or left on its way, so all four directions must be tried
  • Every cell open: the number of paths grows very fast (184 for n = 4, 8512 for n = 5)
  • Forgetting to unmark a cell when backtracking hides paths that pass through it later

Hints

Hint 1

From each cell there are at most four moves. Try each one, go as deep as you can, and undo the move when you come back.

Hint 2

Mark the current cell as used while you are inside it, so the path never steps on the same cell twice. Unmark it before returning.

Hint 3

If you always try the moves in alphabetical order, D, L, R, U, the paths come out already sorted.

FAQ

What is the best time complexity for Rat in a Maze?

Optimal (backtracking in alphabetical order) runs in O(3^(n²) · n²) time and O(n²) extra space. The same routes are explored, so the worst case stays exponential. But a move now costs O(1) instead of a string copy, blocked moves are filtered before the call, and the sort disappears; only saving a finished route copies its up to n² letters.

Which pattern does Rat in a Maze use?

It is a recursion & backtracking problem that uses the 2d matrix backtracking pattern. Other problems with the same pattern: Word Search, Robot Room Cleaner, Sudoku Solver.

Is there a brute force solution for Rat in a Maze?

Yes. Brute force (explore every route, then sort) takes O(3^(n²) · n²) time and O(n²) space. Walk from the top-left cell and try every move in every cell, building the direction string as you go.

Which edge cases should I test for Rat in a Maze?

The start cell (0, 0) is blocked: return an empty list; The exit cell (n - 1, n - 1) is blocked: return an empty list; Both corners are open but walls cut them apart: return an empty list; A path may need to move up or left on its way, so all four directions must be tried; Every cell open: the number of paths grows very fast (184 for n = 4, 8512 for n = 5); Forgetting to unmark a cell when backtracking hides paths that pass through it later.