Sequential Grid Path Cover Problem
Description
LeetCode Problem 3565.
You are given a 2D array grid of size m x n, and an integer k. There are k cells in grid containing the values from 1 to k exactly once, and the rest of the cells have a value 0.
You can start at any cell, and move from a cell to its neighbors (up, down, left, or right). You must find a path in grid which:
- Visits each cell in
gridexactly once. - Visits the cells with values from 1 to
kin order.
Return a 2D array result of size (m * n) x 2, where result[i] = [x_i, y_i] represents the i^th cell visited in the path. If there are multiple such paths, you may return any one.
If no such path exists, return an empty array.
Example 1:
Input: grid = [[0,0,0],[0,1,2]], k = 2
Output: [[0,0],[1,0],[1,1],[1,2],[0,2],[0,1]]
Explanation:

Example 2:
Input: grid = [[1,0,4],[3,0,2]], k = 4
Output: []
Explanation:
There is no possible path that satisfies the conditions.
Constraints:
1 <= m == grid.length <= 51 <= n == grid[i].length <= 51 <= k <= m * n0 <= grid[i][j] <= kgridcontains all integers between 1 andkexactly once.
Solution
Approach: Bitmask + DFS
The grid has at most 25 cells, so a bitmask st can record the visited cells. A valid path must start on a cell with value 0 or 1, because any other value would be visited before the smaller ones.
From each such starting cell, run a DFS that keeps the next required value v (initially 1). On entering a cell, append it to the path and mark it; if its value equals v, increase v. Then try the four neighbors that are unvisited and hold either 0 or the current v. When the path has m * n cells it is complete; otherwise unmark the cell and backtrack. If no start works, return an empty array.
Complexity: exponential in the worst case, but pruned heavily by the value constraint; the space is O(m * n).
class Solution:
def findPath(self, grid: List[List[int]], k: int) -> List[List[int]]:
def f(i: int, j: int) -> int:
return i * n + j
def dfs(i: int, j: int, v: int):
nonlocal st
path.append([i, j])
if len(path) == m * n:
return True
st |= 1 << f(i, j)
if grid[i][j] == v:
v += 1
for a, b in zip(dirs, dirs[1:]):
x, y = i + a, j + b
if (
0 <= x < m
and 0 <= y < n
and (st & 1 << f(x, y)) == 0
and grid[x][y] in (0, v)
):
if dfs(x, y, v):
return True
path.pop()
st ^= 1 << f(i, j)
return False
m, n = len(grid), len(grid[0])
st = 0
path = []
dirs = (-1, 0, 1, 0, -1)
for i in range(m):
for j in range(n):
if grid[i][j] in (0, 1):
if dfs(i, j, 1):
return path
path.clear()
st = 0
return []