Complete a Partially Filled Number Grid with Row, Column, Box Rules
Arrays & HashingAuto-graded · 13 test casesLast updated
Fill in the blanks of a 9x9 digit grid so every row, column and 3x3 block holds each digit 1-9 once, testing backtracking with constraint pruning.
You are given a 9×9 grid that represents a partly completed number-placement puzzle. Each cell holds either a digit character '1' through '9' or the character '.', which marks a blank cell.
Your task is to replace every blank with a digit so that the finished grid obeys all three rules:
- Every row contains each of the digits
1to9exactly once. - Every column contains each of the digits
1to9exactly once. - Each of the nine 3×3 blocks (the grid split into three bands of three rows and three bands of three columns) contains each of the digits
1to9exactly once.
The digits already present in the input must stay unchanged.
Input
grid: a list of 9 lists, each with 9 single-character strings. Each string is'1'..'9'or'.'.
Output
- Return the completed 9×9 grid in the same format (a list of 9 lists of 9 single-character digit strings). You may also fill the input in place, but the returned value must be the finished grid.
Constraints
- The grid is always exactly 9×9.
- Every cell is one of
'1'..'9'or'.'. - The given digits do not contradict each other.
- At least one valid completion exists, and the puzzle is treated as having a single valid completion.
- A grid with no blanks is already complete and is returned unchanged.
Examples
Example 1
Input: complete_number_grid([['5', '3', '.', '.', '7', '.', '.', '.', '.'], ['6', '.', '.', '1', '9', '5', '.', '.', '.'], ['.', '9', '8', '.', '.', '.', '.', '6', '.'], ['8', '.', '.', '.', '6', '.', '.', '.', '3'], ['4', '.', '.', '8', '.', '3', '.', '.', '1'], ['7', '.', '.', '.', '2', '.', '.', '.', '6'], ['.', '6', '.', '.', '.', '.', '2', '8', '.'], ['.', '.', '.', '4', '1', '9', '.', '.', '5'], ['.', '.', '.', '.', '8', '.', '.', '7', '9']])
Output: [['5', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']]
Hints
Hint 1
Keep track of which digits are already used in each row, each column and each 3x3 block. A cell's legal digits are those missing from all three of its groups.
Hint 2
Use plain backtracking: choose a blank, try each legal digit, recurse, and undo the placement if the recursion fails. Make sure you undo both the grid cell and your bookkeeping.
Hint 3
Speed up the search by always picking the blank with the fewest legal digits. A blank with zero options means you should backtrack immediately, and one with a single option is a forced move. Bitmasks make the checks O(1).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a constraint-satisfaction problem solved with backtracking, made fast by two ideas: bitmasks and a fail-first cell choice.
Bitmask bookkeeping. For each row, column and 3x3 block, keep a 9-bit integer where bit d-1 is set when digit d is already used there. A block index is (r // 3) * 3 + (c // 3). The legal digits for a blank at (r, c) are
full & ~(rows[r] | cols[c] | boxes[block])
which costs only a few integer operations.
Choose the most constrained blank. At every step, scan the remaining blanks and pick the one with the fewest legal digits.
- Zero legal digits means the current partial fill is a dead end, so return failure immediately.
- One legal digit is a forced move, so the scan stops early.
Try, recurse, undo. For the chosen blank, take each legal digit (isolating the lowest set bit with mask & -mask), write it into the grid, set the bit in the three masks, and recurse. If the recursion fails, clear the bit from the masks (XOR), restore '.' in the cell, and try the next digit. If all digits fail, put the blank back into the list and report failure to the caller. If the recursion succeeds, return True all the way up without undoing, so the grid stays solved.
Why it is correct
- Soundness: a digit is placed only if it is absent from its row, column and block, so the grid never contains a conflict. When no blanks remain, all 81 cells are filled validly.
- Completeness: every solution must put some legal digit in the chosen blank, and all legal digits are tried, so no solution is skipped. The order of blank selection only affects speed.
- State restoration: every placement is exactly reversed on failure (masks, grid cell, and the blank list), so each recursive call sees the state its parent left.
Complexity
Let m be the number of blanks (at most 81).
- Time: exponential in the worst case (about O(9^m)), with each search node costing O(m) for the scan. Forced-move detection and fail-first ordering prune the search so heavily that standard puzzles are solved with very little backtracking.
- Space: O(m) for the recursion stack and the blank list, plus constant space for the 27 masks. No grid copies are made.
Reference solution
from typing import List
def complete_number_grid(grid: List[List[str]]) -> List[List[str]]:
full = (1 << 9) - 1
rows = [0] * 9
cols = [0] * 9
boxes = [0] * 9
blanks = []
for r in range(9):
for c in range(9):
value = grid[r][c]
if value == '.':
blanks.append((r, c))
else:
bit = 1 << (ord(value) - ord('1'))
b = (r // 3) * 3 + (c // 3)
rows[r] |= bit
cols[c] |= bit
boxes[b] |= bit
def search() -> bool:
if not blanks:
return True
best_index = -1
best_mask = 0
best_count = 10
for i, (r, c) in enumerate(blanks):
b = (r // 3) * 3 + (c // 3)
available = full & ~(rows[r] | cols[c] | boxes[b])
count = bin(available).count('1')
if count < best_count:
best_count = count
best_index = i
best_mask = available
if count == 1:
break
if best_count == 0:
return False
r, c = blanks.pop(best_index)
b = (r // 3) * 3 + (c // 3)
while best_mask:
bit = best_mask & -best_mask
best_mask ^= bit
grid[r][c] = str(bit.bit_length())
rows[r] |= bit
cols[c] |= bit
boxes[b] |= bit
if search():
return True
rows[r] ^= bit
cols[c] ^= bit
boxes[b] ^= bit
grid[r][c] = '.'
blanks.insert(best_index, (r, c))
return False
search()
return grid