You are given an `m x n` integer grid where each cell holds one of four values. A `1` marks the single starting square and a `2` marks the single ending square. A `0` is an empty square you are allowed to walk over, and a `-1` is an obstacle you can never enter.
Starting from the square marked `1`, you may move one step at a time up, down, left, or right to an adjacent in-bounds square that is not an obstacle. A path is considered valid only if it begins at the start, ends at the end, and walks over every non-obstacle square (the start, the end, and all empty squares) exactly once.
Return the number of distinct valid paths that satisfy this requirement.
Example 1
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
There are exactly two four-directional walks that visit every non-obstacle square once and finish on the ending square.
Example 2
Input: grid = [[0,1],[2,0]]
Output: 0
No walk starting at the `1` can cover both remaining empty squares before landing on the `2`, so the answer is zero.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 201 <= m * n <= 20-1 <= grid[i][j] <= 2There is exactly one starting square and exactly one ending square.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI