sagelearnai

Sudoku Solver

Difficulty: Hard · Pattern: Backtracking · LeetCode #37

Fill the empty cells (".") of a 9×9 board so that each row, each column and each 3×3 box contains the digits 1–9 exactly once. The puzzle has exactly one solution. Modify board in place.

Example

text
5 3 . | . 7 . | . . .
6 . . | 1 9 5 | . . .
. 9 8 | . . . | . 6 .
------+-------+------
...                       →  the unique completed grid

Hints

  1. Keep three sets of used digits: per row, per column and per box (box index = (r//3)*3 + c//3). That makes validity checks O(1).
  2. Backtrack: put a digit, recurse, and undo the placement if the recursion fails.
  3. Big speed-up: always fill the empty cell with the fewest legal digits first.

Approach

State: bitmasks rows[r], cols[c], boxes[b], where bit d set means digit d is used.

Search:

text
solve():
    pick the empty cell with the fewest candidates     # MRV heuristic
    if none left: return True
    for each candidate d: place d, update masks
        if solve(): return True
        undo
    return False

MRV (minimum remaining values) makes the search fail fast. A cell with 0 candidates immediately prunes the branch, and cells with 1 candidate act like forced moves (constraint propagation for free). Plain left-to-right backtracking also passes, but MRV is far faster on hard puzzles.

Complexity

Time: exponential in the worst case (bounded by 9^(empty cells)), but MRV makes real puzzles solve in milliseconds. Space: O(81).

Python solution
def solveSudoku(board):
    rows, cols, boxes = [0] * 9, [0] * 9, [0] * 9
    empty = []
    for r in range(9):
        for c in range(9):
            if board[r][c] == '.':
                empty.append((r, c))
            else:
                bit = 1 << int(board[r][c])
                rows[r] |= bit; cols[c] |= bit; boxes[r // 3 * 3 + c // 3] |= bit
    def solve():
        if not empty:
            return True
        best, best_opts = None, None
        for i, (r, c) in enumerate(empty):
            used = rows[r] | cols[c] | boxes[r // 3 * 3 + c // 3]
            opts = [d for d in range(1, 10) if not used >> d & 1]
            if best is None or len(opts) < len(best_opts):
                best, best_opts = i, opts
                if len(opts) <= 1:
                    break
        r, c = empty[best]
        empty[best] = empty[-1]
        empty.pop()
        b = r // 3 * 3 + c // 3
        for d in best_opts:
            bit = 1 << d
            rows[r] |= bit; cols[c] |= bit; boxes[b] |= bit
            board[r][c] = str(d)
            if solve():
                return True
            rows[r] ^= bit; cols[c] ^= bit; boxes[b] ^= bit
        board[r][c] = '.'
        empty.append((r, c))
        empty[best], empty[-1] = empty[-1], empty[best]
        return False
    solve()
JavaScript solution
function solveSudoku(board) {
  const rows = new Array(9).fill(0), cols = new Array(9).fill(0), boxes = new Array(9).fill(0), empty = [];
  for (let r = 0; r < 9; r++) for (let c = 0; c < 9; c++) {
    if (board[r][c] === '.') empty.push([r, c]);
    else { const bit = 1 << Number(board[r][c]); rows[r] |= bit; cols[c] |= bit; boxes[3 * Math.floor(r / 3) + Math.floor(c / 3)] |= bit; }
  }
  const solve = (k) => {
    if (k === empty.length) return true;
    // choose the most constrained remaining cell and swap it into position k
    let best = k, bestCount = 10;
    for (let i = k; i < empty.length; i++) {
      const [r, c] = empty[i], used = rows[r] | cols[c] | boxes[3 * Math.floor(r / 3) + Math.floor(c / 3)];
      let cnt = 0; for (let d = 1; d <= 9; d++) if (!((used >> d) & 1)) cnt++;
      if (cnt < bestCount) { bestCount = cnt; best = i; if (cnt <= 1) break; }
    }
    [empty[k], empty[best]] = [empty[best], empty[k]];
    const [r, c] = empty[k], b = 3 * Math.floor(r / 3) + Math.floor(c / 3);
    const used = rows[r] | cols[c] | boxes[b];
    for (let d = 1; d <= 9; d++) {
      if ((used >> d) & 1) continue;
      const bit = 1 << d;
      rows[r] |= bit; cols[c] |= bit; boxes[b] |= bit; board[r][c] = String(d);
      if (solve(k + 1)) return true;
      rows[r] ^= bit; cols[c] ^= bit; boxes[b] ^= bit;
    }
    board[r][c] = '.';
    return false;
  };
  solve(0);
}