Unique Paths III

You are given an m x n integer array grid where grid[i][j] could be:

  • 1 representing the starting square. There is exactly one starting square.
  • 2 representing the ending square. There is exactly one ending square.
  • 0 representing empty squares we can walk over.
  • -1 representing obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, where the walk visits every non-obstacle square exactly once.

Example 1
 1  0  0  0
 0  0  0  0
 0  0  2 -1
Inputgrid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output2
There are exactly two valid paths that start at the starting square, end at the ending square, and walk over every non-obstacle square exactly once.
Example 2
1 0 0 0
0 0 0 0
0 0 0 2
Inputgrid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output4
There are exactly four valid paths that start at the starting square, end at the ending square, and walk over every non-obstacle square exactly once.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 20
  • 1 <= m * n <= 20
  • -1 <= grid[i][j] <= 2
  • There is exactly one starting cell and one ending cell.

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate