Rat in a Maze

Pattern: Rat in a maze

medium

From the top-left cell, try moving down, left, right and up into open cells not already on the current path, recording the moves. Reaching the bottom-right cell records one path. Unmark each cell on the way back so other paths can use it.

The problem

A rat starts at the top-left cell of an n × n grid and wants to reach the bottom-right cell. Cells with 1 are open and cells with 0 are blocked. The rat moves up (U), down (D), left (L) or right (R), and may not visit a cell twice on one path. Return every path as a string of moves. For example, the grid in the dry run gives DDRDRR and DRDDRR. If there is no path, return an empty list.

The function name findPath matches the takeUforward practice page. Use the link above for the exact statement and limits. The page does not fix an order, so this guide's tests sort the paths.

Think first

  • Why must a cell on the current path be off-limits?
  • When should that mark be removed?
  • What if the start or the goal is blocked?

Hints

    Brute force, and why it fails

    There is no shortcut when every path is wanted: the number of paths itself can be exponential. Backtracking produces each one exactly once.

    The key insight

    "Visited" here means "on the current path", not "seen at some point". Marking on the way in and unmarking on the way out is what lets backtracking list every simple path.

    Dry run

    1 0 0 00 
    1 1 0 11 
    1 1 0 02 
    0 1 1 13 

    The 4 × 4 grid has rows 1 0 0 0, 1 1 0 1, 1 1 0 0 and 0 1 1 1. Start at the top-left.

    Step 1 of 4

    The plan

    if grid[0][0] == 0 or grid[n-1][n-1] == 0: return []
    function walk(r, c, path):
        if (r, c) is the goal: record path; return
        mark (r, c)
        for each move (D, L, R, U) to an open, unmarked cell: walk(next, path + move)
        unmark (r, c)
    walk(0, 0, "")
    

    Complexity

    Time
    O(4^(n²)) worst
    Space
    O(n²)

    Each cell offers up to 4 moves, so the worst case is exponential in the grid size; n ≤ 5 keeps it small. The marks and the recursion use O(n²).

    Edge cases

    • Start blocked: no paths.
    • Goal unreachable: no paths.
    • A fully open grid: many paths, all without repeated cells.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<String> findPath(int[][] grid) {
            int n = grid.length;
            List<String> out = new ArrayList<>();
            if (grid[0][0] == 0 || grid[n - 1][n - 1] == 0) return out;
            walk(grid, 0, 0, new boolean[n][n], new StringBuilder(), out);
            return out;
        }
    
        private static final int[] DR = {1, 0, 0, -1}, DC = {0, -1, 1, 0};
        private static final char[] MOVE = {'D', 'L', 'R', 'U'};
    
        private void walk(int[][] g, int r, int c, boolean[][] seen, StringBuilder path, List<String> out) {
            int n = g.length;
            if (r == n - 1 && c == n - 1) { out.add(path.toString()); return; }
            seen[r][c] = true;                              // no cell twice on one path
            for (int k = 0; k < 4; k++) {
                int nr = r + DR[k], nc = c + DC[k];
                if (nr < 0 || nc < 0 || nr >= n || nc >= n || g[nr][nc] == 0 || seen[nr][nc]) continue;
                path.append(MOVE[k]);
                walk(g, nr, nc, seen, path, out);
                path.deleteCharAt(path.length() - 1);
            }
            seen[r][c] = false;                             // free the cell for other paths
        }
    }

    C++

    class Solution {
    public:
        vector<string> findPath(vector<vector<int>>& grid) {
            int n = static_cast<int>(grid.size());
            vector<string> out;
            if (grid[0][0] == 0 || grid[n - 1][n - 1] == 0) return out;
            vector<vector<bool>> seen(n, vector<bool>(n, false));
            string path;
            walk(grid, 0, 0, seen, path, out);
            return out;
        }
    
        void walk(vector<vector<int>>& g, int r, int c, vector<vector<bool>>& seen, string& path, vector<string>& out) {
            static const int DR[4] = {1, 0, 0, -1}, DC[4] = {0, -1, 1, 0};
            static const char MOVE[4] = {'D', 'L', 'R', 'U'};
            int n = static_cast<int>(g.size());
            if (r == n - 1 && c == n - 1) { out.push_back(path); return; }
            seen[r][c] = true;                              // no cell twice on one path
            for (int k = 0; k < 4; k++) {
                int nr = r + DR[k], nc = c + DC[k];
                if (nr < 0 || nc < 0 || nr >= n || nc >= n || g[nr][nc] == 0 || seen[nr][nc]) continue;
                path.push_back(MOVE[k]);
                walk(g, nr, nc, seen, path, out);
                path.pop_back();
            }
            seen[r][c] = false;                             // free the cell for other paths
        }
    };

    Python

    class Solution:
        def findPath(self, grid: list[list[int]]) -> list[str]:
            n = len(grid)
            out = []
            if grid[0][0] == 0 or grid[n - 1][n - 1] == 0:
                return out
            seen = [[False] * n for _ in range(n)]
            moves = [(1, 0, "D"), (0, -1, "L"), (0, 1, "R"), (-1, 0, "U")]
    
            def walk(r: int, c: int, path: list) -> None:
                if r == n - 1 and c == n - 1:
                    out.append("".join(path))
                    return
                seen[r][c] = True                   # no cell twice on one path
                for dr, dc, m in moves:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] and not seen[nr][nc]:
                        path.append(m)
                        walk(nr, nc, path)
                        path.pop()
                seen[r][c] = False                  # free the cell for other paths
    
            walk(0, 0, [])
            return out

    Common mistakes

    • Never unmarking, which hides paths that share a cell.
    • Checking the cell's value before checking it is inside the grid.
    • Forgetting that the start cell itself must be marked.

    Similar problems