Sudoku Solver (LeetCode 37): Solution and Explanation
You are given a partially filled 9 × 9 Sudoku board with empty cells marked by a dot. Fill every empty cell in place so each row, each column and each of the nine 3 × 3 boxes contains the digits 1 to 9 exactly once; the puzzle is guaranteed to have one solution.
Watch it run step by step
Try your own input and write the code →Intuition
The most naive brute force fills all empty cells with every combination of digits and then checks the board, which is 9 to the power of the number of blanks complete boards. That is hopeless for a typical puzzle with 50 or more blanks. The improvement that makes it practical is to check constraints as you go, so you abandon a partial board the moment it breaks a rule instead of finishing it first.
That is backtracking. Find the first empty cell, try the digits 1 through 9 in turn, and for each digit that does not already appear in the same row, column or box, place it and recursively solve the rest of the board. If the recursive call succeeds, the whole puzzle is solved and you stop. If it fails, some later cell had no legal digit, so you erase your choice and try the next digit. If no digit works, you report failure to the caller, which then changes its own earlier choice.
The power of this approach comes from pruning. Most digits are rejected immediately by the validity check, so the search tree is far smaller than the theoretical 9 to the m. Real puzzles usually solve in milliseconds even though the worst-case bound is exponential.
The reference code keeps things simple. It checks validity by scanning the row, column and box each time, and each call to solve rescans the board from the top-left to find the next empty cell. Both are constant work on a fixed 9 × 9 board, so they only affect speed by a constant factor.
Approach: Backtracking with constraint checks
- Define
isValid(row, col, num)that returns False ifnumalready appears in that row, that column or that 3 × 3 box, whose top-left corner is(3 * (row // 3), 3 * (col // 3)). - Define
solve()that scans the board for the first cell equal to '.'. - For that cell, try each digit from '1' to '9' and skip any that fail
isValid. - Place a valid digit and call
solve()recursively; if it returns True, propagate True upward. - If the recursive call fails, reset the cell to '.' and try the next digit.
- If no digit fits, return False; if the scan finds no empty cell at all, return True because the board is complete.
Step-by-step example
The standard example board, whose first row is ["5","3",".",".","7",".",".",".","."]
- The first empty cell is row 0, column 2. Its row already contains 5, 3 and 7, its column contains 8, and its top-left box contains 5, 3, 6, 9 and 8.
- That leaves 1, 2 and 4 as legal digits. The solver places 1, the smallest, and recurses into row 0, column 3.
- The search keeps filling cells this way. Somewhere later a cell runs out of legal digits, so that call returns False and the most recent choice is erased and replaced with the next candidate.
- Because the puzzle has a unique solution in which this cell is 4, every branch that starts with 1 or 2 eventually fails and unwinds back here.
- With 4 placed, the recursion fills the remaining cells, reaches a board with no '.', returns True and leaves the solved board in place.
Code: Python, Java, C++
1class Solution:
2 def solveSudoku(self, board: List[List[str]]) -> None:
3 def isValid(row, col, num):
4 # Check row
5 if num in board[row]:
6 return False
7 # Check column
8 for r in range(9):
9 if board[r][col] == num:
10 return False
11 # Check 3x3 box
12 boxRow, boxCol = 3 * (row // 3), 3 * (col // 3)
13 for r in range(boxRow, boxRow + 3):
14 for c in range(boxCol, boxCol + 3):
15 if board[r][c] == num:
16 return False
17 return True
18
19 def solve():
20 for i in range(9):
21 for j in range(9):
22 if board[i][j] == '.':
23 for num in '123456789':
24 if isValid(i, j, num):
25 board[i][j] = num
26 if solve():
27 return True
28 board[i][j] = '.'
29 return False
30 return True
31
32 solve()1class Solution {
2 public void solveSudoku(char[][] board) {
3 solve(board);
4 }
5
6 private boolean solve(char[][] board) {
7 for (int i = 0; i < 9; i++) {
8 for (int j = 0; j < 9; j++) {
9 if (board[i][j] == '.') {
10 for (char num = '1'; num <= '9'; num++) {
11 if (isValid(board, i, j, num)) {
12 board[i][j] = num;
13 if (solve(board)) return true;
14 board[i][j] = '.';
15 }
16 }
17 return false;
18 }
19 }
20 }
21 return true;
22 }
23
24 private boolean isValid(char[][] board, int row, int col, char num) {
25 for (int i = 0; i < 9; i++) {
26 if (board[row][i] == num) return false;
27 if (board[i][col] == num) return false;
28 int boxRow = 3 * (row / 3) + i / 3;
29 int boxCol = 3 * (col / 3) + i % 3;
30 if (board[boxRow][boxCol] == num) return false;
31 }
32 return true;
33 }
34}1class Solution {
2public:
3 void solveSudoku(vector<vector<char>>& board) {
4 solve(board);
5 }
6
7private:
8 bool solve(vector<vector<char>>& board) {
9 for (int i = 0; i < 9; i++) {
10 for (int j = 0; j < 9; j++) {
11 if (board[i][j] == '.') {
12 for (char num = '1'; num <= '9'; num++) {
13 if (isValid(board, i, j, num)) {
14 board[i][j] = num;
15 if (solve(board)) return true;
16 board[i][j] = '.';
17 }
18 }
19 return false;
20 }
21 }
22 }
23 return true;
24 }
25
26 bool isValid(vector<vector<char>>& board, int row, int col, char num) {
27 for (int i = 0; i < 9; i++) {
28 if (board[row][i] == num) return false;
29 if (board[i][col] == num) return false;
30 int boxRow = 3 * (row / 3) + i / 3;
31 int boxCol = 3 * (col / 3) + i % 3;
32 if (board[boxRow][boxCol] == num) return false;
33 }
34 return true;
35 }
36};Time and space complexity
O(9^m)
With m empty cells, each cell tries at most 9 digits, so the search tree is bounded by 9 to the m. Each validity check and board scan is constant work on a fixed 9 × 9 board. In practice pruning makes it far faster than this bound.
O(m)
The recursion goes one level deeper for every filled cell, so the stack depth is at most m, which is at most 81. The board is modified in place.
Other approaches
Backtracking with constraint sets (time O(9^m), space O(m))
Keep a set (or bitmask) of used digits for each row, column and box, so validity checks become O(1) lookups. Update the sets when placing and removing digits. Same search, noticeably faster.
Most constrained cell first (time O(9^m), space O(m))
At each step pick the empty cell with the fewest legal digits instead of the first one. This heuristic shrinks the search tree dramatically on hard puzzles at the cost of scanning candidates.
Common mistakes
- Forgetting to reset the cell to '.' after a failed recursive call leaves a wrong digit on the board and corrupts later validity checks.
- Returning False only after looping over all cells, instead of right after the digit loop for the first empty cell, lets the solver skip past a cell it could not fill.
- Computing the box corner as
row // 3instead of3 * (row // 3)checks the wrong cells. - Comparing against integers when the board holds characters, so digits like '5' never match 5 and every placement looks valid.
Frequently asked questions
How does backtracking solve Sudoku?
It fills empty cells one at a time with digits that do not break any rule and recurses. When a later cell has no legal digit, it undoes the most recent choice and tries the next one, until the board is full.
What is the time complexity of the Sudoku solver?
The worst-case bound is O(9^m) for m empty cells, since each can take up to 9 values. Constraint checks prune most branches, so real puzzles finish quickly.
How do you speed up a Sudoku solver?
Track used digits per row, column and box with sets or bitmasks for O(1) checks, and choose the empty cell with the fewest options first. Both cut the search dramatically.
Why does solve return a boolean?
The boolean tells the caller whether the rest of the board was completed. On True, every level stops and keeps its digit; on False, the caller undoes its choice and tries another.