Sudoku Solver

Hard

Topics
ArrayBacktrackingMatrix

Fill a 9 by 9 Sudoku grid so that every row, every column, and each of the nine 3 by 3 boxes contains the digits 1 to 9 exactly once. Empty cells are marked ..

Each generated puzzle has exactly one solution.

LeetCode gives the board as char[][] and asks you to modify it in place, and the harness here honours that: the argument is named grid, you may mutate it and return nothing, and the judge reads whatever the board holds afterwards. Returning a new board works too. Rows arrive as nine-character strings.

Example 1

puzzle53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79
solved534678912672195348198342567859761423426853791713924856961537284287419635345286179
givenfilled in
This puzzle starts with 51 blanks and 30 given digits. Each row, each column and each of the nine boxes has to end up holding 1 to 9 once apiece, and those three constraints together are what pin every blank down. Exactly one completion satisfies all of them, which is the lower board.
A box is a 3 by 3 block, so the cell at row r and column c belongs to box (r / 3, c / 3).
Input:  grid = ["53..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"]
Output: ["534678912","672195348","198342567","859761423","426853791","713924856","961537284","287419635","345286179"]
Explanation: The classic puzzle. Every blank is forced once enough of its row, column and box are known.

Example 2

puzzle53467891.672195348198342567859761423426853791713924856961537284287419635345286179
solved534678912672195348198342567859761423426853791713924856961537284287419635345286179
givenfilled in
Input:  grid = ["53467891.","672195348","198342567","859761423","426853791","713924856","961537284","287419635","345286179"]
Output: ["534678912","672195348","198342567","859761423","426853791","713924856","961537284","287419635","345286179"]
Explanation: One blank, so only one digit is missing from that row.

Example 3

puzzle534678912672195348198342567859761423426853791713924856961537284287419635345286179
solved534678912672195348198342567859761423426853791713924856961537284287419635345286179
given
Nothing is blank, so the board is already its own answer and must come back unchanged.
Input:  grid = ["534678912","672195348","198342567","859761423","426853791","713924856","961537284","287419635","345286179"]
Output: ["534678912","672195348","198342567","859761423","426853791","713924856","961537284","287419635","345286179"]
Explanation: An already-complete board. Nothing to do, and the board must come back unchanged.

Constraints

  • grid.length == 9
  • grid[i].length == 9
  • grid[i][j] is a digit 1-9 or the character .
  • The puzzle has exactly one solution
Editorial — intuition, approach, complexity and pitfalls

Intuition

Trying every digit in every blank is hopeless if done blindly, but the structure of Sudoku makes blind search unnecessary. A digit placed in a cell is either legal against the three groups that cell belongs to or it is not, and that can be checked immediately rather than at the end.

So the shape is: find a blank, try each digit that is currently legal there, and recurse. If the recursion fails for every digit, the cell has no legal value given the choices above it — so undo the last placement and try the next digit there. That undo is the whole technique.

The reason this terminates quickly in practice is that an illegal placement is caught at the moment of placing, not thirty cells later. Most branches die one step in.

What makes the difference between fast and slow is which blank you pick next. Picking the first blank in reading order works. Picking the blank with the fewest legal digits works much better, because it either forces a single choice or proves the branch dead right away — if some blank has no legal digit, there is no point exploring the other blanks at all.

Approach

  1. Keep, for each row, each column and each box, the set of digits already used. A cell at (r, c) is in box (r / 3) * 3 + c / 3.
  2. Find a blank cell. Scanning in reading order is correct; choosing the blank with the fewest candidates is faster.
  3. For each digit not in the cell’s row set, column set or box set: write it, add it to all three sets, and recurse.
  4. If the recursion reports success, propagate that success and stop. Otherwise erase the digit, remove it from the three sets, and try the next one.
  5. When no blank remains, the board is complete — report success so the recursion unwinds without undoing anything.

Walkthrough

a corner of the board

   5 3 . | . 7 .
   6 . . | 1 9 5
   . 9 8 | . . .

cell (0,2)
   row 0 already has 5 3 7
   col 2 already has 8
   box 0 already has 5 3 6 9 8
   legal digits: 1 2 4

   try 1 -> recurse. Somewhere deeper a cell runs out of
            legal digits, so that branch fails and 1 is erased.
   try 2 -> recurse. Succeeds, so 2 stays and the answer
            unwinds without further search.

why fewest-candidates-first helps
   if some blank has 0 legal digits, picking it immediately
   proves the branch dead. Picking a different blank first
   explores a whole subtree before discovering the same thing.

Complexity

  • Time — exponential in the worst case: the search tree is bounded by 9 choices per blank, but legality pruning kills almost every branch immediately, so real puzzles finish in milliseconds.
  • Space — O(1): the board is fixed at 81 cells and the recursion is at most 81 deep; the used-digit sets are 27 sets of at most 9 digits.

Common Pitfalls

  • Checking the box with the wrong index. It is (r / 3) * 3 + c / 3; mixing up the row and column factors silently validates the wrong nine cells.
  • Forgetting to erase the digit and remove it from the three sets when a branch fails. The board is then left dirty and later placements are rejected for no reason.
  • Returning after the first successful placement instead of after the recursion succeeds. Success has to come from the bottom of the recursion.
  • Validating the whole board after each placement rather than checking the one new digit. Correct, but needlessly slow.
  • Comparing digits as integers in one place and as characters in another. The board holds characters.

Full Solution — all languages

class Solution:
    def solveSudoku(self, board):
        def ok(r, c, v):
            br, bc = r - r % 3, c - c % 3
            for i in range(9):
                if board[r][i] == v or board[i][c] == v:
                    return False
                if board[br + i // 3][bc + i % 3] == v:
                    return False
            return True

        def solve():
            for r in range(9):
                for c in range(9):
                    if board[r][c] != '.':
                        continue
                    for v in "123456789":
                        if not ok(r, c, v):
                            continue
                        board[r][c] = v
                        if solve():
                            return True
                        board[r][c] = '.'      # undo and try the next digit
                    return False               # no digit fits: this branch is dead
            return True                        # no blank left: solved

        solve()
SensAI
Beta
Tap the mic to stop voice mode