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[][], with a digit in each given cell and '.' in each empty one. Fill the empty cells so that every row, every column and every 3 x 3 box holds each digit from 1 to 9 exactly once. The puzzle has exactly one solution, and the board must be changed in place.

Example
Input: the board below, given row by row
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
Solution

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..... Its first empty cell is row 0, column 2. Which digits could go there? Row 0 already has 5, 3 and 7. Column 2 has an 8, two rows down. Box 0 holds 5, 3, 6, 9 and 8. That leaves 1, 2 and 4.

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 choice tree for the cell at row 0, column 2. Digits 3, 5 and 7 are in row 0, 6 and 9 are in box 0, and 8 is in column 2, so those branches are cut short. Digit 1 leads to row 0, column 3, where 2 and 6 both fail later and are undone; 333 digits are placed in branch 1, all undone. Digit 2 places 1,874 digits, all undone. Digit 4 is kept and the search fills all 51 empty cells.

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 cell sits at row cell / 9 and column cell % 9. A method fill(board, cell) handles one cell and then calls itself for cell + 1, so each call waits on the call for the next cell. A cell with a given digit has nothing to choose, so it just passes on to the next cell.

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] is true when row r already holds digit d, and colHas and boxHas do the same for columns and boxes. The tables are filled from the given digits at the start, and a check is then three lookups.

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 / 3 is the band. In the same way c / 3 is the position inside the band. The box number is (r / 3) * 3 + c / 3. For example, the cell at row 4, column 7 is in box (4 / 3) * 3 + 7 / 3 = 3 + 2 = 5, the middle box on the right.

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 '.'. Every change is reversed in this way, so the board and the tables look exactly as they did before that digit was tried.

Stopping at a full board

When is the work done? When fill is called with cell 81, every cell has a digit, so it returns true. Each waiting call sees true and returns at once without undoing its digit. That way the solved board stays in place. If no digit fits a cell, fill returns false, and the call before it tries its next digit.

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 works in these steps:

  1. The three tables rowHas, colHas and boxHas are fields, created empty with the object. Each is 9 x 10, so a digit d from 1 to 9 can be used as an index directly.
  2. First, walk the board with two loops, one inside the other, over rows r and columns c. For every given digit, call mark(r, c, d, true), which sets the entry for that digit in the row, column and box tables.
  3. Call fill(board, 0). It returns true at cell 81, and passes a cell with a given digit straight on to fill(board, cell + 1).
  4. For an empty cell, a loop tries each digit d from 1 to 9 and skips it when rowHas, colHas or boxHas already has it. The box index comes from box(r, c).
  5. For a digit that fits, write it into the board, mark it, and call fill for the next cell. On true, return true. Otherwise unmark the digit, write '.' back, and try the next one.
  6. When the loop runs out of digits, return false, so the previous empty cell tries its next digit.

The main method solves the example, a solved board with one cell emptied, and a board with every cell empty.

Java
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:

Output
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, where the 4 is the digit the picture showed being kept. Under "One empty cell:" the board had a '.' in row 4, column 4. Only 5 fits there, and the row now reads 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 way there was still not straight: a run that counted the steps placed 391 digits and undid 310 of them before all 81 cells held one.

The box formula needs its * 3. With r / 3 + c / 3, the cells at row 0, column 3 and at row 3, column 0 both get box 1, so a digit in one box blocks it in another. We ran the example with that formula: fill returned false and the board came back with all 51 empty cells still empty.

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 fill wait on each other, one per cell plus the call for cell 81, whatever the puzzle.