1779. Balanced Binary Grid

Medium3.5 points estimatedBacktrackingMatrixHash Table

A tile workshop lays out an n x n floor with black and white tiles, where n is even. The array grid holds '0' for white, '1' for black and '.' for a tile not yet placed.

Replace every '.' in place, returning nothing, so that: every row and every column has exactly n/2 zeros and n/2 ones; no row or column contains three equal symbols in a row; and no two rows are identical and no two columns are identical. The given tiles are consistent and the puzzle has exactly one completion, so no tie-break is needed. Fill cells in row-major order, checking only the row and column of the new cell, and keep completed lines in a hash set. Intended complexity: backtracking with pruning and O(n^2) extra space.

Example 1

Input:
grid = [[".","0",".","."],["1",".",".","."],[".",".","1","1"],[".",".",".","0"]]
Output:
[["1","0","0","1"],["1","1","0","0"],["0","0","1","1"],["0","1","1","0"]]
Explanation:

The 4x4 board has 11 blanks; the unique completion balances every row and column, avoids three equal neighbours and repeats no line.

Example 2

Input:
grid = [["1",".",".",".","1","."],[".",".","0",".",".","."],["0",".",".","1",".","."],["0",".",".",".",".","."],[".","1",".",".","0","."],[".",".","0",".",".","."]]
Output:
[["1","0","1","0","1","0"],["1","1","0","0","1","0"],["0","0","1","1","0","1"],["0","0","1","0","1","1"],["1","1","0","1","0","0"],["0","1","0","1","0","1"]]
Explanation:

The 6x6 board has 27 blanks; the unique completion balances every row and column, avoids three equal neighbours and repeats no line.

Constraints

4 ≤ n ≤ 8 and n is even
Each cell is '0', '1' 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 grid after your method returns.

Expected complexity

Time
O(2^(n^2)) worst case, heavily pruned
Space
O(n^2)

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…