Skip to problem
←

Unique Paths III

Hard 0 attempts

Given a rectangular grid, count paths from the starting cell to the ending cell that visit every non-obstacle cell exactly once.

  • 1: the single starting cell.
  • 2: the single ending cell.
  • 0: an empty cell that must be visited.
  • -1: an obstacle that cannot be visited.

Each move goes one cell up, down, left, or right. Diagonal moves are not allowed. The start and end also count as visited cells. A path must stop at the end; reaching it before visiting all other open cells does not count.

Return the number of valid paths, or 0 if none exists. Paths are distinct when their ordered sequences of visited cells differ.

Function contract

Implement uniquePathsIII(grid).

Output: Return the number of paths that visit every non-obstacle cell exactly once and finish at the ending cell.

Example 1

Input
grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output
2

Example 2

Input
grid = [[1,2]]
Output
1
Visual Aid
Visit every open cell before finishing
StartEndDown → right → up → right → down

For [[1,0,0],[0,0,2]], this route visits all six cells. Going right, right, down reaches the end too early and does not count.

Constraints
  • 1 <= m, n <= 20
  • m * n <= 20
  • grid is rectangular; every cell is -1, 0, 1, or 2.
  • There is exactly one starting cell (1) and exactly one ending cell (2).

Backtracking

Count all non-obstacle cells, including the start and end. Search from the start, temporarily marking each visited cell as blocked. Restore its original value after exploring its neighbors so other candidate paths can use it.

remaining includes the current cell. At the ending cell, count the path only when remaining === 1; otherwise stop that branch because the end cannot be used as an intermediate cell.

javascript
function uniquePathsIII(grid) {
  const rows = grid.length, cols = grid[0].length;
  let startR, startC, empty = 0;

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] !== -1) empty++;
      if (grid[r][c] === 1) { startR = r; startC = c; }
    }
  }

  let count = 0;
  function dfs(r, c, remaining) {
    if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] === -1) return;
    if (grid[r][c] === 2) {
      if (remaining === 1) count++;
      return;
    }
    const original = grid[r][c];
    grid[r][c] = -1;
    for (const [dr, dc] of [[1,0],[-1,0],[0,1],[0,-1]]) {
      dfs(r + dr, c + dc, remaining - 1);
    }
    grid[r][c] = original;
  }

  dfs(startR, startC, empty);
  return count;
}

Time: O(3^(m·n)) — after the first move, returning to the previous cell is forbidden, leaving at most 3 choices Space: O(m·n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript