Sudoku Solver
Pattern: Sudoku
Find the first empty cell and try digits 1 to 9 that are not already in its row, column or 3 × 3 box. For each, recurse; if the rest cannot be filled, put the cell back to empty and try the next digit.
The problem
Fill a 9 × 9 Sudoku board in place. Empty cells are '.'. In the finished board each row, each column and each of the
nine 3 × 3 boxes contains every digit from 1 to 9 exactly once. The puzzle has exactly one solution.
The function name solveSudoku matches LeetCode. Use the link above for the exact statement and limits. This guide's
tests print the nine rows of the solved board joined by spaces.
Think first
- Which three groups does one cell belong to?
- What do you do when no digit fits a cell?
- When can the whole search stop?
Hints
Brute force, and why it fails
Try every way to fill the empty cells and then check the board: up to 9^(empty cells). Checking each digit as it is
placed prunes most of that at once.
The key insight
The rules can be checked one cell at a time, so wrong guesses are caught immediately instead of at the end. That turns an impossible search into one that finishes in milliseconds for normal puzzles.
Dry run
| cell | (0, 2) |
|---|
The first empty cell of the example board is row 0, column 2. Row 0 already has 5, 3 and 7, column 2 has 8, and its box has 5, 3, 6, 9 and 8.
The plan
function solve():
find the first empty cell (r, c); if none: return true
for d in '1'..'9':
if fits(r, c, d):
board[r][c] = d
if solve(): return true
board[r][c] = '.'
return false
Complexity
- Time
O(9^m) worst- Space
O(m)
m is the number of empty cells, at most 81. Real puzzles need far fewer steps because of pruning. The recursion is m
deep.
Edge cases
- A board with one empty cell: one digit fits.
- Harder puzzles take longer with this simple order; picking the most constrained cell first helps.
- The board is changed in place; nothing is returned.
I've built my logic, show the code
Java
class Solution {
public void solveSudoku(char[][] board) {
solve(board);
}
private boolean solve(char[][] b) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (b[r][c] != '.') continue; // the first empty cell
for (char d = '1'; d <= '9'; d++) {
if (!fits(b, r, c, d)) continue;
b[r][c] = d;
if (solve(b)) return true; // the rest worked out
b[r][c] = '.'; // undo and try the next digit
}
return false; // no digit fits here: go back
}
}
return true; // no empty cell left
}
private boolean fits(char[][] b, int r, int c, char d) {
for (int i = 0; i < 9; i++) {
if (b[r][i] == d || b[i][c] == d) return false; // row and column
if (b[r / 3 * 3 + i / 3][c / 3 * 3 + i % 3] == d) return false; // 3 x 3 box
}
return true;
}
}C++
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
bool solve(vector<vector<char>>& b) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (b[r][c] != '.') continue; // the first empty cell
for (char d = '1'; d <= '9'; d++) {
if (!fits(b, r, c, d)) continue;
b[r][c] = d;
if (solve(b)) return true; // the rest worked out
b[r][c] = '.'; // undo and try the next digit
}
return false; // no digit fits here: go back
}
}
return true; // no empty cell left
}
bool fits(vector<vector<char>>& b, int r, int c, char d) {
for (int i = 0; i < 9; i++) {
if (b[r][i] == d || b[i][c] == d) return false; // row and column
if (b[r / 3 * 3 + i / 3][c / 3 * 3 + i % 3] == d) return false; // 3 x 3 box
}
return true;
}
};Python
class Solution:
def solveSudoku(self, board: list[list[str]]) -> None:
def fits(r: int, c: int, d: str) -> bool:
for i in range(9):
if board[r][i] == d or board[i][c] == d: # row and column
return False
if board[r // 3 * 3 + i // 3][c // 3 * 3 + i % 3] == d: # 3 x 3 box
return False
return True
def solve() -> bool:
for r in range(9):
for c in range(9):
if board[r][c] != ".":
continue # the first empty cell
for d in "123456789":
if fits(r, c, d):
board[r][c] = d
if solve():
return True # the rest worked out
board[r][c] = "." # undo and try the next digit
return False # no digit fits here: go back
return True # no empty cell left
solve()Common mistakes
- Getting the box corner wrong.
- Not resetting a cell after a failed guess.
- Searching on after success, which undoes the solution.