HardArrayBacktrackingBit ManipulationMatrix

1 approach, code in every language

Problem description

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.length
  • n == grid[i].length
  • 1 <= m, n <= 20
  • 1 <= m * n <= 20
  • -1 <= grid[i][j] <= 2
  • There is exactly one starting square and exactly one ending square.

After the pattern

Now solve one you haven't seen.

Sweeping Every Open Bay Once is our own problem on the technique behind Unique Paths III: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free