Unique Paths III

You are given an `m x n` grid where `1` is the start, `2` is the end, `0` is an empty square and `-1` is an obstacle. Return the number of 4-directional walks from the start to the end that step on every non-obstacle square exactly once.

30:00

Unique Paths III
hard
Free written solution
Topics
Companies

You are given an m x n grid where 1 is the start, 2 is the end, 0 is an empty square and -1 is an obstacle. Return the number of 4-directional walks from the start to the end that step on every non-obstacle square exactly once.

Example 1:
Input: {"grid":[[1,0,0,0],[0,0,0,0],[0,0,2,-1]]}
Output: 2
Constraints:
  • m==grid.lengthm == \text{grid.length}

  • n==grid[i].lengthn == \text{grid[i].length}

  • 1≤m,n≤201 \leq m, n \leq 20

  • 1≤m⋅n≤201 \leq m \cdot n \leq 20

  • −1≤grid[i][j]≤2-1 \leq \text{grid}[i][j] \leq 2

  • There is exactly one starting cell and one ending cell.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[1,0,0,0],[0,0,0,0],[0,0,2,-1]]}

Count the squares the walk must cover: 9 empty squares plus the start gives 10. A walk counts only if it reaches the 2 with none left.

walks found

0

to cover

10

walk length

0

grid: the walk so far

S
E

S start

E end

numbers = step order

striped = obstacle

squares covered

0 of 10 required squares visited

Variables
VariableValue
atnull
remain10
count0
empty10
DepthFunction Call
Stack empty
0/111