Sudoku Solver

Solve a Sudoku puzzle in place via backtracking with row/col/box bitmasks.

Hard
Time O(9^k) Space O(1)
LeetCode
6 min read
backtracking bitmask

Problem#

Fill the empty cells (.) of a partial 9×9 Sudoku board to form a valid solution. Exactly one solution exists.

Approach#

Track row/col/box usage as 9-bit masks. DFS over cells left-to-right, top-to-bottom; for each empty cell, try every digit not in its row/col/box mask. Recurse; on failure, unset and try the next digit.

Solution#

Sudoku Solver
class Solution {
public:
void solveSudoku(vector<vector<char>>& b) {
int rows[9] = {0}, cols[9] = {0}, boxes[9] = {0};
for (int r = 0; r < 9; ++r)
for (int c = 0; c < 9; ++c)
if (b[r][c] != '.') {
int bit = 1 << (b[r][c] - '1');
rows[r] |= bit; cols[c] |= bit; boxes[(r/3)*3 + c/3] |= bit;
}
function<bool(int)> dfs = [&](int pos) {
if (pos == 81) return true;
int r = pos / 9, c = pos % 9, k = (r/3)*3 + c/3;
if (b[r][c] != '.') return dfs(pos + 1);
int used = rows[r] | cols[c] | boxes[k];
for (int d = 0; d < 9; ++d) {
int bit = 1 << d;
if (used & bit) continue;
b[r][c] = '1' + d;
rows[r] |= bit; cols[c] |= bit; boxes[k] |= bit;
if (dfs(pos + 1)) return true;
rows[r] ^= bit; cols[c] ^= bit; boxes[k] ^= bit;
b[r][c] = '.';
}
return false;
};
dfs(0);
}
};

Editorial#

Bitmasks per row/col/box make “is digit d available here?” a single bitwise-and. The DFS order (left-to-right, top-to-bottom) is sufficient; advanced heuristics (most-constrained-cell first) cut typical solve times but aren’t needed.

Complexity#

  • Time: O(9^k) where k is the number of empty cells.
  • Space: O(1) auxiliary.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.