Sequential Grid Path Cover - Problem

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 grid exactly once
  • Visits the cells with values from 1 to k in order

Return a 2D array result of size (m * n) x 2, where result[i] = [xi, yi] represents the ith 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.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[1,2],[3,0]], k = 3
Output: [[0,0],[0,1],[1,0],[1,1]]
💡 Note: Start at (0,0) with value 1, move to (0,1) with value 2, then (1,0) with value 3, finally (1,1) with value 0. This visits all numbered cells 1→2→3 in order and covers all cells exactly once.
Example 2 — No Solution
$ Input: grid = [[2,1],[0,0]], k = 2
Output: []
💡 Note: Must visit cell with value 1 before cell with value 2, but they are positioned such that any Hamiltonian path visits 2 before 1, making a solution impossible.
Example 3 — Single Row
$ Input: grid = [[0,1,2,0]], k = 2
Output: [[0,0],[0,1],[0,2],[0,3]]
💡 Note: Simple path from left to right visits 1 then 2 in correct order while covering all cells.

Constraints

  • 1 ≤ m, n ≤ 4
  • 1 ≤ k ≤ m × n
  • 0 ≤ grid[i][j] ≤ k
  • Each value from 1 to k appears exactly once in grid

Visualization

Tap to expand
Sequential Grid Path CoverInput Grid1230(0,0)(0,1)(1,0)(1,1)Valid Path1230Output[[0,0],[0,1],[1,0],[1,1]]Visit order:1. (0,0) → cell value 1 ✓2. (0,1) → cell value 2 ✓3. (1,0) → cell value 3 ✓Constraint: Visit numbered cells in order 1 → 2 → 3Requirement: Visit all cells exactly once (Hamiltonian Path)Solution: Backtracking with Sequential Constraint Checking
Understanding the Visualization
1
Input Grid
2D grid with numbered cells 1 to k and zeros
2
Find Path
Create path visiting all cells exactly once
3
Check Order
Ensure numbered cells are visited in sequence 1→2→...→k
4
Output Path
Return coordinates of cells in visit order
Key Takeaway
🎯 Key Insight: Use backtracking to explore Hamiltonian paths while enforcing sequential ordering constraints
Asked in
Google 15 Facebook 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen