1778. Diagonal Latin Fill
A puzzle club prints small square boards for a weekend contest. Each board is an n x n grid held in grid. A cell holds a digit from '1' to 'n' or a dot '.' for a blank.
Fill every blank, modifying grid in place and returning nothing, so that each row, each column, the main diagonal and the anti-diagonal contain every digit from '1' to 'n' exactly once. The given digits never conflict and the puzzle has exactly one completion, so no tie-break is needed. Choose the blank with the fewest legal digits at each step and track used digits with row, column and diagonal bitmasks. Intended complexity: backtracking with pruning, O(n^2) extra space.
Example 1
- Input:
- grid = [["4",".",".","."],[".",".",".","."],[".","2","3","."],[".",".",".","."]]
- Output:
- [["4","3","2","1"],["2","1","4","3"],["1","2","3","4"],["3","4","1","2"]]
- Explanation:
The 4x4 puzzle has 13 blank cells; the unique completion puts each digit once in every row, column and both diagonals.
Example 2
- Input:
- grid = [[".","2","1",".","."],[".",".",".",".","."],[".",".",".","4","5"],[".",".",".",".","."],[".",".",".",".","1"]]
- Output:
- [["4","2","1","5","3"],["2","5","3","1","4"],["3","1","2","4","5"],["1","4","5","3","2"],["5","3","4","2","1"]]
- Explanation:
The 5x5 puzzle has 20 blank cells; the unique completion puts each digit once in every row, column and both diagonals.
Constraints
4 ≤ n ≤ 7
Each cell is a digit '1'..'n' or '.'
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
gridafter your method returns.
Expected complexity
- Time
- O(n!) worst case with pruning
- Space
- O(n^2)