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 Cover INPUT 1 2 3 0 [0,0] [0,1] [0] [1] grid = [[1,2],[3,0]] k = 3 m=2, n=2 (2x2 grid) Must visit cells 1, 2, 3 in sequential order Visit every cell exactly once ALGORITHM STEPS 1 Find Start Position Locate cell with value 1 Start: [0,0] 2 DFS/Backtracking Try all 4 directions Track visited cells 3 Check Sequence Verify 1 --> 2 --> 3 order Next target updates 4 Validate Path All cells visited once Return path or backtrack 1 2 3 4 Path order: 1-->2-->3-->4 FINAL RESULT 1 2 3 4 Output: [[0,0],[0,1], [1,0],[1,1]] 4 positions OK - Valid Path All cells visited once Sequence 1,2,3 preserved Key Insight: Use DFS with backtracking. Start from cell containing 1, track next required value (1 to k). When visiting a numbered cell, it must match the next expected value. Backtrack if stuck. Time: O(4^(m*n)) worst case | Space: O(m*n) for recursion and visited tracking TutorialsPoint - Sequential Grid Path Cover | Optimal Solution (DFS + Backtracking)
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