Skip to problem
←

All Paths Through a Maze

Medium 0 attempts

Given a square binary matrix maze, return every path from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1). A numeric 1 is open and a 0 is blocked.

Move one cell at a time in four directions: D (down), L (left), R (right), or U (up). Stay within the matrix and never visit the same cell twice within one path. Different paths may share cells.

Return each route once as its sequence of move letters, in any order. Find all valid paths, not just shortest ones. Stop a route when it first reaches the destination. Return [] if either endpoint is blocked or no route exists. For a one-cell open maze, return [""]: the start is already the destination and no moves are needed.

For [[1, 1], [1, 1]], the routes are "DR" and "RD". Diagonal moves are not allowed.

Function contract

Implement findPath(maze).

Output: Return each valid route once as a string of D, L, R, and U moves. Outer order does not matter. Return [] for no route and [""] for an open 1×1 maze.

Example 1

Input
maze = [[1,0,0,0],[1,1,0,1],[1,1,0,0],[0,1,1,1]]
Output
["DDRDRR","DRDDRR"]

Example 2

Input
maze = [[0]]
Output
[]
Constraints
  • 1 <= maze.length <= 5
  • maze is square; maze[i][j] is 0 or 1
  • Paths cannot revisit cells.

Backtracking with a Visited Grid

Mark the starting cell visited. From each open cell, try every valid neighboring cell that is not already on the current route. Mark it before descending and unmark it afterward. Unmarking allows other routes to reuse that cell while still preventing cycles within a route.

Keep moves in one shared array. When the destination is reached, join the moves into a result string and stop that branch. The empty move array correctly represents the open one-cell maze. Reject a blocked endpoint immediately.

javascript
function findPath(maze) {
  const n = maze.length;
  if (!maze[0][0] || !maze[n - 1][n - 1]) return [];
  const result = [];
  const visited = Array.from({ length: n }, () => Array(n).fill(false));
  const moves = [];
  const directions = [
    ["D", 1, 0],
    ["L", 0, -1],
    ["R", 0, 1],
    ["U", -1, 0],
  ];
  function visit(r, c) {
    if (r === n - 1 && c === n - 1) {
      result.push(moves.join(""));
      return;
    }
    for (const [letter, dr, dc] of directions) {
      const nr = r + dr,
        nc = c + dc;
      if (
        nr < 0 ||
        nr >= n ||
        nc < 0 ||
        nc >= n ||
        !maze[nr][nc] ||
        visited[nr][nc]
      )
        continue;
      visited[nr][nc] = true;
      moves.push(letter);
      visit(nr, nc);
      moves.pop();
      visited[nr][nc] = false;
    }
  }
  visited[0][0] = true;
  visit(0, 0);
  return result;
}

Time: O(4^(n²) + P) as a loose upper bound, where P is the total number of move characters returned. The search is exponential because it enumerates simple paths.

Space: O(n²) auxiliary space for the visited grid, recursion, and current moves, plus O(P + R) for R returned route strings. The input maze is not modified.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript