1806. Number Snake Fill

Hard7.5 points estimatedBacktrackingMatrixDepth-First Search

A game board is an r x c grid of integers. A zero marks an empty cell, and any other value is a clue that is fixed in place. Fill every empty cell so that the numbers 1 to r*c each appear exactly once and, for every k below r*c, the cell holding k is orthogonally adjacent to the cell holding k+1, so the numbers form one continuous snake. All clues must stay where they are, and the cell holding 1 is always a clue.

Modify grid in place; the function returns nothing. Exactly one filling exists, so there is no tie to break. Walk the snake from 1 with backtracking, jumping from clue to clue, and prune a branch as soon as the Manhattan distance to the next clue is larger than the gap between the two numbers.

Example 1

Input:
grid = [[1]]
Output:
[[1]]
Explanation:

The 1 clue(s) force exactly one snake through all 1 cells.

Example 2

Input:
grid = [[3,0,0],[0,0,0],[1,0,9]]
Output:
[[3,4,5],[2,7,6],[1,8,9]]
Explanation:

The 3 clue(s) force exactly one snake through all 9 cells.

Example 3

Input:
grid = [[1,0,0,16],[0,0,0,15],[0,0,5,14],[0,0,0,13]]
Output:
[[1,2,3,16],[8,7,4,15],[9,6,5,14],[10,11,12,13]]
Explanation:

The 6 clue(s) force exactly one snake through all 16 cells.

Constraints

1 ≤ r, c ≤ 6

0 marks an empty cell; the clues are distinct values in 1..r*c and 1 is among them

Exactly one filling exists

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from grid after your method returns.

Expected complexity

Time
Pruned backtracking, tiny for r, c <= 6
Space
O(r * c)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…