1804. Picture Clue Grid

Hard7.5 points estimatedBacktrackingMatrixBitmask

A picture puzzle hides a drawing inside a rows x cols grid. At the start every cell of grid is '?'. For each row i, rowClues[i] lists, from left to right, the lengths of the maximal runs of filled cells in that row, and colClues[j] does the same for column j from top to bottom. A line with no filled cell is written as [0]. Two runs in a line are always separated by at least one empty cell.

Fill grid in place, writing '#' into every filled cell and '.' into every empty cell; the function returns nothing. The clues allow exactly one drawing, so no tie-break is needed. Precompute every valid pattern of each row as a bitmask, place the rows one at a time, and prune whenever the top part of some column can no longer match its clue.

Example 1

Input:
grid = [["?","?","?"],["?","?","?"],["?","?","?"]]rowClues = [[1,1],[1],[2]]colClues = [[3],[1],[1]]
Output:
[["#",".","#"],["#",".","."],["#","#","."]]
Explanation:

Exactly one drawing on this 3 x 3 grid matches all row and column clues; '#' marks filled cells.

Example 2

Input:
grid = [["?","?","?","?","?"],["?","?","?","?","?"],["?","?","?","?","?"],["?","?","?","?","?"],["?","?","?","?","?"]]rowClues = [[2,1],[2],[3],[3],[2]]colClues = [[1,1],[5],[1,2],[2],[1]]
Output:
[[".","#","#",".","#"],["#","#",".",".","."],[".","#","#","#","."],[".","#","#","#","."],["#","#",".",".","."]]
Explanation:

Exactly one drawing on this 5 x 5 grid matches all row and column clues; '#' marks filled cells.

Example 3

Input:
grid = [["?","?","?","?","?","?"],["?","?","?","?","?","?"],["?","?","?","?","?","?"],["?","?","?","?","?","?"]]rowClues = [[4,1],[2,3],[1],[1,3]]colClues = [[2],[2,1],[1],[2,1],[3],[2,1]]
Output:
[["#","#","#","#",".","#"],["#","#",".","#","#","#"],[".",".",".",".","#","."],[".","#",".","#","#","#"]]
Explanation:

Exactly one drawing on this 4 x 6 grid matches all row and column clues; '#' marks filled cells.

Constraints

1 ≤ rows, cols ≤ 8

grid starts all '?'; every clue list is non-empty and [0] means an empty line

Exactly one drawing satisfies the clues

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 over row masks
Space
O(rows * 2^cols + cols * 2^rows * rows)

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…