1805. Crossword Filler

Hard7.5 points estimatedBacktrackingMatrixStringHash Table

A newspaper grid consists of blocked cells '#' and open cells '.'. A slot is a maximal horizontal run (read left to right) or maximal vertical run (read top to bottom) of at least two open cells. You get exactly as many distinct uppercase words as there are slots. Put every word into exactly one slot of the same length, one word per slot, so that wherever two slots cross, the two words show the same letter in the shared cell.

Write the letters into grid in place; the function returns nothing. Every open cell lies in at least one slot, and exactly one valid assignment exists, so there is no tie-break. Backtrack by always choosing the unplaced slot that has the fewest words still fitting its pattern of already known letters.

Example 1

Input:
grid = [[".",".","."],[".",".","."]]words = ["JE","EFB","DB","KF","JKD"]
Output:
[["J","K","D"],["E","F","B"]]
Explanation:

The 5 words fit the 5 slots in exactly one way with every crossing letter agreeing.

Example 2

Input:
grid = [["#","#","#","."],["#","#",".","."],["#","#","#","."],[".",".",".","."]]words = ["ILGJ","IGBJ","DL"]
Output:
[["#","#","#","I"],["#","#","D","L"],["#","#","#","G"],["I","G","B","J"]]
Explanation:

The 3 words fit the 3 slots in exactly one way with every crossing letter agreeing.

Example 3

Input:
grid = [["#",".",".","#","."],["#","#",".","#","."],["#",".",".","#","."],["#","#",".",".","."],["#",".",".","#","."]]words = ["DAB","JD","II","DHADI","AEJBI","IA"]
Output:
[["#","J","D","#","A"],["#","#","H","#","E"],["#","I","A","#","J"],["#","#","D","A","B"],["#","I","I","#","I"]]
Explanation:

The 6 words fit the 6 slots in exactly one way with every crossing letter agreeing.

Constraints

1 ≤ rows, cols ≤ 8, grid cells are '#' or '.'

Words are distinct, uppercase A-Z, and words.length equals the number of slots, at most 16

Every open cell lies in a slot; 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, at most 16! orderings in theory
Space
O(slots * cells)

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…