Sequential Grid Path Cover - Problem

πŸ—ΊοΈ Sequential Grid Path Cover

Imagine you're exploring a treasure map represented as a 2D grid of size m Γ— n. The grid contains k special treasure cells numbered from 1 to k, with all other cells marked as 0.

Your mission is to find a path that:

  • Visits every single cell in the grid exactly once (no cell left behind!)
  • Collects treasures in order - you must visit cells containing values 1, 2, 3, ..., k in that exact sequence

You can start at any cell and move to adjacent cells (up, down, left, right). Return the complete path as a 2D array where each element [x, y] represents the coordinates of the i-th cell visited.

Challenge: If multiple valid paths exist, return any one. If no path exists, return an empty array.

Input & Output

example_1.py β€” Simple 2x3 Grid
$ Input: grid = [[1, 0, 3], [0, 2, 0]]
β€Ί Output: [[0,0], [0,1], [1,1], [1,2], [0,2], [1,0]]
πŸ’‘ Note: Start at (0,0) with value 1, move to collect 2 at (1,1), then 3 at (0,2), while visiting all cells exactly once
example_2.py β€” Single Row
$ Input: grid = [[1, 2, 3]]
β€Ί Output: [[0,0], [0,1], [0,2]]
πŸ’‘ Note: Simple path from left to right collecting numbered cells in sequence
example_3.py β€” Impossible Case
$ Input: grid = [[1, 3], [2, 0]]
β€Ί Output: []
πŸ’‘ Note: No valid path exists - cannot visit all cells while collecting 1,2,3 in order from these positions

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≀ m, n ≀ 4
  • 0 ≀ grid[i][j] ≀ m * n
  • Each value from 1 to k appears exactly once
  • k ≀ m * n

Visualization

Tap to expand
Sequential Grid Path Cover StrategyNumbered cells (treasures)Empty cellsValid path132STARTPath: (0,0) β†’ (1,0) β†’ (1,1) β†’ (1,2) β†’ (0,2) β†’ (0,1)Collects treasures in order: 1 β†’ 2 β†’ 3 while visiting all cellsAlgorithm Steps:1. Try each cell as starting position2. Use DFS to explore all possible paths3. Ensure numbered cells visited in sequence4. Backtrack when constraints violated
Understanding the Visualization
1
Map Analysis
Identify positions of numbered cells (treasures) and plan route
2
Path Exploration
Try different starting positions and use backtracking to find valid paths
3
Constraint Validation
Ensure numbered cells are visited in correct order (1, 2, 3, ...)
4
Complete Coverage
Verify all cells are visited exactly once
Key Takeaway
🎯 Key Insight: Break the problem into phases - reach each numbered cell in order while ensuring complete grid coverage through backtracking exploration.
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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