Sudoku Solver
Fill the empty cells of a 9 x 9 Sudoku by placing digits one cell at a time and undoing the ones that lead nowhere.
A 9 x 9 Sudoku board is stored as a char[][]'.'
Example
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
The Idea
If you have solved a Sudoku in a newspaper, you know the grid: nine rows, nine columns, and thick lines that split it into nine 3 x 3 squares, called boxes. We number rows and columns from 0 to 8, and the boxes 0 to 8 from left to right and top to bottom, so box 0 is the top-left square.
Look at the first row of the example, 53..7....
Three digits are possible, and nothing in this one cell tells us which is right. A person would look elsewhere for a cell with a single choice. A program can do something simpler: put in the smallest digit that fits, 1, and move on to the next empty cell. If, some cells later, an empty cell has no digit left at all, then a digit placed earlier was wrong. The program undoes digits, back to the most recent cell that still has an untried digit, and tries that one.
Placing a digit, going on, and stepping back to undo it when the board runs into a cell with no digit left is called backtracking. The choices form a tree. Look at the picture below.
The rectangle at the top is the cell at row 0, column 2, and the nine rectangles under it are the digits 1 to 9. The dashed ones are cut short: 3, 5 and 7 are marked "in row 0", 6 and 9 "in box 0", and 8 "in column 2". They are never placed, so nothing grows under them.
Under 1 the search moves to the next empty cell, row 0, column 3, where only 2 and 6 fit. Both fail later and are undone, so the 1 is undone too. That branch placed 333 digits, every one of them taken back. The digit 2 fares no better, with 1,874 digits placed and undone. With 4 the search goes on and fills all 51 empty cells, and 4 is indeed the digit in row 0, column 2 of the answer.
So the program never needs to be clever about which digit to try. It needs two things: a fast way to tell whether a digit fits a cell, and a clean way to undo a digit.
Solution Approach
Turning that idea into code means settling four things: the order of the cells, how to check a digit quickly, how to undo it, and how to stop once the board is full. A smarter order of the cells is an optional extra.
The order of the cells
In which order should the cells be filled? Reading order is the simplest. Number the 81 cells from 0 to 80, row by row, so cell number cellcell / 9cell % 9fill(board, cell)cell + 1
Checking a digit in three lookups
How do we know whether a digit fits? Scanning the row, the column and the box means reading 27 cells for every digit tried. Instead, keep three tables of booleans: rowHas[r][d]rdcolHasboxHas
Which box is a cell in? Rows 0 to 2 form the top band of boxes, rows 3 to 5 the middle band, and rows 6 to 8 the bottom band, so r / 3c / 3(r / 3) * 3 + c / 3
Placing and undoing a digit
What exactly happens when a digit is placed? It is written into the board and marked in all three tables. If the call for the next cell fails, the same digit is unmarked and the cell is set back to '.'
Stopping at a full board
When is the work done? When filltruetruefillfalse
Optional: the cell with the fewest choices first
Could the search waste less work? Reading order may reach a cell with no digit left only after many cells, as branch 1 in the picture shows. A common improvement picks, at every step, the empty cell with the fewest digits that still fit. A wrong guess then shows up sooner, closer to where it was made. The code below keeps reading order, which is simpler and solves the example quickly.
Java Solution
The method solveSudoku
- The three tables
,rowHas andcolHas are fields, created empty with the object. Each is 9 x 10, so a digitboxHas from 1 to 9 can be used as an index directly.d - First, walk the board with two loops, one inside the other, over rows
and columnsr . For every given digit, callc , which sets the entry for that digit in the row, column and box tables.mark(r, c, d, true) - Call
. It returnsfill(board, 0) at cell 81, and passes a cell with a given digit straight on totrue .fill(board, cell + 1) - For an empty cell, a loop tries each digit
from 1 to 9 and skips it whend ,rowHas orcolHas already has it. The box index comes fromboxHas .box(r, c) - For a digit that fits, write it into the board, mark it, and call
for the next cell. Onfill , returntrue . Otherwise unmark the digit, writetrue back, and try the next one.'.' - When the loop runs out of digits, return
, so the previous empty cell tries its next digit.false
The main
public class SudokuSolver {
private final boolean[][] rowHas = new boolean[9][10]; // rowHas[r][d]: digit d is in row r
private final boolean[][] colHas = new boolean[9][10]; // colHas[c][d]: digit d is in column c
private final boolean[][] boxHas = new boolean[9][10]; // boxHas[b][d]: digit d is in box b
public void solveSudoku(char[][] board) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] != '.') {
mark(r, c, board[r][c] - '0', true);
}
}
}
fill(board, 0);
}
// Fill the empty cells in order; cell is a number 0..80 (row * 9 + column)
private boolean fill(char[][] board, int cell) {
if (cell == 81) {
return true; // every cell is filled
}
int r = cell / 9;
int c = cell % 9;
if (board[r][c] != '.') {
return fill(board, cell + 1); // given digit: nothing to choose
}
for (int d = 1; d <= 9; d++) {
if (rowHas[r][d] || colHas[c][d] || boxHas[box(r, c)][d]) {
continue; // d breaks a rule here
}
board[r][c] = (char) ('0' + d); // place d
mark(r, c, d, true);
if (fill(board, cell + 1)) { // try to fill the rest
return true; // solved: keep this board
}
mark(r, c, d, false); // undo d
board[r][c] = '.';
}
return false; // no digit fits: an earlier digit was wrong
}
private void mark(int r, int c, int d, boolean value) {
rowHas[r][d] = value;
colHas[c][d] = value;
boxHas[box(r, c)][d] = value;
}
private static int box(int r, int c) {
return (r / 3) * 3 + c / 3; // boxes 0..8, left to right, top to bottom
}
static void solveAndPrint(String title, String... rows) {
char[][] board = new char[9][];
for (int r = 0; r < 9; r++) {
board[r] = rows[r].toCharArray();
}
new SudokuSolver().solveSudoku(board);
System.out.println(title);
for (char[] row : board) {
System.out.println(new String(row));
}
}
public static void main(String[] args) {
solveAndPrint("Example:",
"53..7....", "6..195...", ".98....6.",
"8...6...3", "4..8.3..1", "7...2...6",
".6....28.", "...419..5", "....8..79");
solveAndPrint("One empty cell:",
"534678912", "672195348", "198342567",
"859761423", "4268.3791", "713924856",
"961537284", "287419635", "345286179");
String empty = ".........";
solveAndPrint("Empty board:",
empty, empty, empty, empty, empty, empty, empty, empty, empty);
}
}
Running it prints:
Example:
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
One empty cell:
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
Empty board:
123456789
456789123
789123456
214365897
365897214
897214365
531642978
642978531
978531642
The nine rows under "Example:" match the expected output, starting with 534678912'.'426853791
The empty board breaks the one-solution promise of the problem, since many boards fit it. The search keeps the first full board it reaches, and because small digits are tried first, the first row is 123456789
The box formula needs its * 3r / 3 + c / 3fillfalse
Complexity
The cost depends on how many digits are placed and undone before the search reaches the full board.
- Time: O(9m) in the worst case, for m empty cells, because each empty cell can try up to 9 digits for every way the cells before it were filled, and each check is three table lookups. Real puzzles take far less: the example places 4,208 digits in all for its 51 empty cells.
- Space: O(1), because the three tables always hold 9 x 10 booleans each and at most 82 calls of
wait on each other, one per cell plus the call for cell 81, whatever the puzzle.fill