1803. Inequality Grid Fill

Hard7.5 points estimatedBacktrackingMatrixBitmask

A puzzle club prints an n x n board that must be filled so every row and every column contains each digit from 1 to n exactly once. In grid some cells already hold a digit character and the empty cells hold '.'. Each entry [r1, c1, r2, c2] of relations names two orthogonally adjacent cells and says that the digit at (r1, c1) is strictly smaller than the digit at (r2, c2). Rows and columns are numbered from 0.

Write the complete solution into grid in place, using the characters '1' to 'n'; the function returns nothing. The puzzle has exactly one solution, so there is no tie to break. Keep a bitmask of candidates for every cell, tighten the masks along the relations, and branch on the cell with the fewest candidates. With n at most 7 the pruned search is tiny.

Example 1

Input:
grid = [["3",".",".","."],[".",".",".","1"],[".",".",".","3"],[".",".","4","."]]relations = [[1,0,0,0],[2,2,1,2],[2,1,2,2],[2,2,2,3],[3,1,3,2],[3,3,3,2],[3,0,3,1],[2,1,2,0],[1,0,1,1],[0,1,1,1],[2,1,3,1],[1,3,0,3]]
Output:
[["3","2","1","4"],["2","4","3","1"],["4","1","2","3"],["1","3","4","2"]]
Explanation:

Exactly one Latin square fits the 4 preset digits and 12 relations, and it is written into grid.

Example 2

Input:
grid = [["2",".","3","."],[".",".",".","4"],["4",".",".","2"],["1",".",".","."]]relations = []
Output:
[["2","4","3","1"],["3","1","2","4"],["4","3","1","2"],["1","2","4","3"]]
Explanation:

Exactly one Latin square fits the 6 preset digits and 0 relations, and it is written into grid.

Example 3

Input:
grid = [[".",".",".",".","."],[".","5",".","1","4"],[".",".",".",".","."],["5",".",".",".","3"],[".",".","4",".","."]]relations = [[4,0,4,1],[0,3,0,2],[1,3,0,3],[1,2,0,2],[2,0,3,0],[1,2,1,1],[2,1,3,1],[0,1,1,1],[2,1,2,0],[3,4,4,4],[1,0,0,0],[2,4,3,4],[4,1,3,1],[3,1,3,0],[1,3,2,3],[1,0,1,1]]
Output:
[["3","1","5","4","2"],["2","5","3","1","4"],["4","3","2","5","1"],["5","4","1","2","3"],["1","2","4","3","5"]]
Explanation:

Exactly one Latin square fits the 6 preset digits and 16 relations, and it is written into grid.

Constraints

4 ≤ n ≤ 7, grid is n x n of '.' or '1'..'n'

0 ≤ relations.length ≤ 40

The puzzle has exactly one solution

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 n <= 7
Space
O(n^2 + relations.length)

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…