37. Sudoku Solver
Asked at 15Amazon48Bloomberg47Google46Microsoft46Meta29Apple22Confluent97Snap80Arcesium61Citadel57Uber55eBay53Zoho42DoorDash36Oracle27
Problem
Fill the empty cells ('.') of a 9×9 Sudoku board in place so that every row, column and 3×3 box contains the digits 1–9 exactly once. The puzzle has exactly one solution.
Example: a standard puzzle → its unique completed grid
Track used digits per row/col/box (bitmasks or sets). Find an empty cell, try every allowed digit, recurse; undo on failure. (Heuristic: fill the cell with the fewest candidates first.)
Complexity: exponential worst case; fast in practice.
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
empty = []
for r in range(9):
for c in range(9):
v = board[r][c]
if v == ".":
empty.append((r, c))
else:
rows[r].add(v); cols[c].add(v); boxes[r // 3 * 3 + c // 3].add(v)
def bt(k):
if k == len(empty):
return True
r, c = empty[k]
b = r // 3 * 3 + c // 3
for v in "123456789":
if v in rows[r] or v in cols[c] or v in boxes[b]:
continue
board[r][c] = v
rows[r].add(v); cols[c].add(v); boxes[b].add(v)
if bt(k + 1):
return True
rows[r].remove(v); cols[c].remove(v); boxes[b].remove(v)
board[r][c] = "."
return False
bt(0)
B = ["53..7....", "6..195...", ".98....6.", "8...6...3", "4..8.3..1", "7...2...6", ".6....28.", "...419..5", "....8..79"]
board = [list(r) for r in B]
Solution().solveSudoku(board)
assert ["".join(r) for r in board][0] == "534678912" and ["".join(r) for r in board][8] == "345286179"
assert ["".join(r) for r in board] == ['534678912', '672195348', '198342567', '859761423', '426853791', '713924856', '961537284', '287419635', '345286179']
class Solution {
private final boolean[][] row = new boolean[9][10], col = new boolean[9][10], box = new boolean[9][10];
public void solveSudoku(char[][] board) {
for (int r = 0; r < 9; r++)
for (int c = 0; c < 9; c++)
if (board[r][c] != '.') mark(r, c, board[r][c] - '0', true);
bt(board, 0);
}
private void mark(int r, int c, int d, boolean v) { row[r][d] = col[c][d] = box[r / 3 * 3 + c / 3][d] = v; }
private boolean bt(char[][] b, int k) {
if (k == 81) return true;
int r = k / 9, c = k % 9;
if (b[r][c] != '.') return bt(b, k + 1);
for (int d = 1; d <= 9; d++) {
if (row[r][d] || col[c][d] || box[r / 3 * 3 + c / 3][d]) continue;
b[r][c] = (char) ('0' + d);
mark(r, c, d, true);
if (bt(b, k + 1)) return true;
mark(r, c, d, false);
}
b[r][c] = '.';
return false;
}
}
func solveSudoku(board [][]byte) {
var rows, cols, boxes [9][10]bool
empty := [][2]int{}
for r := 0; r < 9; r++ {
for c := 0; c < 9; c++ {
if board[r][c] == '.' {
empty = append(empty, [2]int{r, c})
} else {
v := board[r][c] - '0'
rows[r][v], cols[c][v], boxes[r/3*3+c/3][v] = true, true, true
}
}
}
var bt func(k int) bool
bt = func(k int) bool {
if k == len(empty) {
return true
}
r, c := empty[k][0], empty[k][1]
b := r/3*3 + c/3
for v := byte(1); v <= 9; v++ {
if rows[r][v] || cols[c][v] || boxes[b][v] {
continue
}
board[r][c] = '0' + v
rows[r][v], cols[c][v], boxes[b][v] = true, true, true
if bt(k + 1) {
return true
}
rows[r][v], cols[c][v], boxes[b][v] = false, false, false
}
board[r][c] = '.'
return false
}
bt(0)
}