Sudoku Solver
Hard
Topics
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
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
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
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
- 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. - Find a blank cell. Scanning in reading order is correct; choosing the blank with the fewest candidates is faster.
- 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.
- 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.
- 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()import java.util.*;
class Solution {
public void solveSudoku(char[][] board) {
cells = board;
solve();
}
private char[][] cells;
private boolean fits(int r, int c, char v) {
int br = r - r % 3, bc = c - c % 3;
for (int i = 0; i < 9; i++) {
if (cells[r][i] == v || cells[i][c] == v) return false;
if (cells[br + i / 3][bc + i % 3] == v) return false;
}
return true;
}
private boolean solve() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (cells[r][c] != '.') continue;
for (char v = '1'; v <= '9'; v++) {
if (!fits(r, c, v)) continue;
cells[r][c] = v;
if (solve()) return true;
cells[r][c] = '.';
}
return false;
}
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: void solveSudoku(vector<vector<char>>& board) {
auto ok = [&](int r, int c, char v) {
int br = r - r % 3, bc = c - c % 3;
for (int i = 0; i < 9; i++) {
if (board[r][i] == v || board[i][c] == v) return false;
if (board[br + i / 3][bc + i % 3] == v) return false;
}
return true;
};
function<bool()> solve = [&]() -> bool {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] != '.') continue;
for (char v = '1'; v <= '9'; v++) {
if (!ok(r, c, v)) continue;
board[r][c] = v;
if (solve()) return true;
board[r][c] = '.';
}
return false;
}
}
return true;
};
solve();
}
};/**
* @param {character[][]} board
* @return {character[][]}
*/ var solveSudoku = function(board) {
const ok = (r, c, v) => {
const br = r - r % 3, bc = c - c % 3;
for (let i = 0; i < 9; i++) {
if (board[r][i] === v || board[i][c] === v) return false;
if (board[br + Math.floor(i / 3)][bc + i % 3] === v) return false;
}
return true;
};
const solve = () => {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (board[r][c] !== ".") continue;
for (let d = 1; d <= 9; d++) {
const v = String(d);
if (!ok(r, c, v)) continue;
board[r][c] = v;
if (solve()) return true;
board[r][c] = ".";
}
return false;
}
}
return true;
};
solve();
};