Valid Sudoku

Check whether the digits on a partly filled Sudoku board repeat in any row, column or 3 x 3 box.

You are given a 9 x 9 Sudoku board as a char[][]. Some cells hold a digit from '1' to '9', and empty cells hold '.'. Return true if the filled cells follow three rules, and false otherwise:

Only the digits already on the board are checked. A board can be valid even if it has no solution.

Example 1
Input: board =
5 3 . | . 7 . | . . .
6 . . | 1 9 5 | . . .
. 9 8 | . . . | . 6 .
8 . . | . 6 . | . . 3
4 . . | 8 . 3 | . . 1
7 . . | . 2 . | . . 6
. 6 . | . . . | 2 8 .
. . . | 4 1 9 | . . 5
. . . | . 8 . | . 7 9
Output: true
Example 2
Input: the same board, with the 5 in the top-left corner changed to 8
Output: false
Explanation: the top-left 3 x 3 box now has two 8s.
Solution

The Idea

You have probably seen a Sudoku puzzle in a newspaper: a 9 x 9 grid, split into nine 3 x 3 boxes, with some digits already filled in. The player fills in the rest so that every row, every column and every box holds each digit from 1 to 9 exactly once. Here nobody plays. We only look at the digits already written in and ask whether two of them clash.

Look at the picture below. On the left is the board of Example 2, with its rows and columns numbered 0 to 8. Cell (2, 2) means row 2, column 2. The 8 at (0, 0) is circled, and so is the 8 at (2, 2). Both sit in the shaded top-left box, so the board breaks the box rule. In Example 1 the corner holds a 5 instead, and no digit repeats anywhere.

Left: the board of Example 2 with rows and columns numbered 0 to 8. The 8 at (0, 0) and the 8 at (2, 2) are circled, both in the shaded top-left box, box 0. Right: the nine boxes numbered 0 to 8, with the formula box = (r / 3) * 3 + c / 3.

The 8 at (0, 0) clashes a second time, too. Look down column 0: row 3 also holds an 8. One broken rule is already enough to make the board invalid.

How would you find such clashes by hand? For each digit, you could look along its row, down its column and around its box for a copy. That means reading the same rows over and over. It is quicker to read the board once, cell by cell, and keep a note for every row, every column and every box of the digits met so far. When a digit arrives that its row, column or box has already noted, there is a repeat.

So the whole check is one pass over the board with 27 notes: nine for the rows, nine for the columns and nine for the boxes. The right half of the picture numbers the boxes 0 to 8, so that each cell can find its box's note.

Solution Approach

Turning that idea into code means settling three things: how to keep the notes, how to tell which box a cell is in, and when to stop reading.

Keeping the notes

What does a note need to hold? Only a yes or no for each of the nine digits. Without notes, each filled cell needs 24 comparisons: 8 with the other cells in its row, 8 in its column and 8 in its box. With notes, each check is a single lookup.

One boolean[9][9] table holds the notes of all nine rows. Digit 1 gets index 0, digit 2 gets index 1, and so on, so inRow[r][d] becomes true once row r has the digit d + 1. Two more tables, inCol and inBox, do the same for columns and boxes. To turn the character '1' into index 0, the code subtracts: a char is stored as a number, and '1' to '9' have consecutive numbers, so ch - '1' gives 0 for '1' and 8 for '9'.

Finding a cell's box

Which box is cell (r, c) in? Dividing by 3 answers it. When Java divides one int by another, it drops the remainder. So r / 3 is 0 for rows 0 to 2, 1 for rows 3 to 5 and 2 for rows 6 to 8. In the same way, c / 3 tells which of the three box columns the cell is in.

The right half of the picture numbers the boxes from left to right, top to bottom. Each row of boxes holds three, so the number is (r / 3) * 3 + c / 3. For cell (2, 2) that is 0 * 3 + 0, box 0. For cell (4, 7) it is 1 * 3 + 2, box 5, the middle box on the right.

When to stop

Does the method have to read the whole board? Only when the board is valid. The first repeat already decides the answer, so the method returns false right there. Empty cells carry no digit, so they are skipped and never marked.

Java Solution

The method isValidSudoku works in these steps:

  1. First, create the three tables of notes, inRow, inCol and inBox, each a boolean[9][9]. Java fills new boolean arrays with false, so every note starts empty.
  2. Visit every cell with two loops, one inside the other. The outer loop moves r over the rows, and the inner loop moves c over the columns. Read the cell into ch, and skip it if it is '.'.
  3. Turn the digit into an index with d = ch - '1', and work out the cell's box with box = (r / 3) * 3 + c / 3.
  4. If inRow[r][d], inCol[c][d] or inBox[box][d] is already true, the digit repeats, so return false.
  5. Otherwise set all three notes to true and go on. When both loops finish without a repeat, return true.

The main method builds each board from nine strings, one per row. It checks both examples, an empty board, a row with two 4s, a column with two 7s, and a board with a 1 at (0, 3) and another at (3, 0).

Java
public class ValidateSudoku {

    public static boolean isValidSudoku(char[][] board) {
        boolean[][] inRow = new boolean[9][9];   // inRow[r][d]: digit d + 1 already in row r
        boolean[][] inCol = new boolean[9][9];   // inCol[c][d]: digit d + 1 already in column c
        boolean[][] inBox = new boolean[9][9];   // inBox[b][d]: digit d + 1 already in box b
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                char ch = board[r][c];
                if (ch == '.') {
                    continue;                    // empty cell: nothing to check
                }
                int d = ch - '1';                // '1' -> 0, ..., '9' -> 8
                int box = (r / 3) * 3 + c / 3;   // boxes 0..8, left to right, top to bottom
                if (inRow[r][d] || inCol[c][d] || inBox[box][d]) {
                    return false;                // this digit was seen before
                }
                inRow[r][d] = true;
                inCol[c][d] = true;
                inBox[box][d] = true;
            }
        }
        return true;
    }

    static char[][] board(String... rows) {
        char[][] b = new char[9][];
        for (int r = 0; r < 9; r++) {
            b[r] = rows[r].toCharArray();
        }
        return b;
    }

    public static void main(String[] args) {
        String[] example1 = {
            "53..7....", "6..195...", ".98....6.",
            "8...6...3", "4..8.3..1", "7...2...6",
            ".6....28.", "...419..5", "....8..79"};
        System.out.println(isValidSudoku(board(example1)));

        String[] example2 = example1.clone();
        example2[0] = "83..7....";                       // top-left 5 changed to 8
        System.out.println(isValidSudoku(board(example2)));

        String empty = ".........";
        System.out.println(isValidSudoku(board(empty, empty, empty, empty, empty,
                empty, empty, empty, empty)));

        System.out.println(isValidSudoku(board(            // two 4s in row 0, boxes 0 and 2
                "4......4.", empty, empty, empty, empty, empty, empty, empty, empty)));

        System.out.println(isValidSudoku(board(            // two 7s in column 4
                "....7....", empty, empty, empty, empty, empty, empty, "....7....", empty)));

        System.out.println(isValidSudoku(board(            // 1 at (0, 3) and at (3, 0)
                "...1.....", empty, empty, "1........", empty, empty, empty, empty, empty)));
    }
}

Running it prints:

Output
true
false
true
false
false
true

Example 1 prints true and Example 2 prints false. For Example 2 the loops stop at (2, 2): the 8 there finds box 0 already marked. They never reach the 8 at (3, 0), the clash in column 0. The empty board prints true, since every cell is skipped.

The two false lines that follow each come from a single table. The two 4s in row 0 sit in boxes 0 and 2, so only inRow catches them. The two 7s in column 4 sit in boxes 1 and 7, so only inCol catches them.

The last line, true, tests the box formula. Cell (0, 3) is in box 1 and cell (3, 0) in box 3, so the two 1s do not clash. A shorter formula, r / 3 + c / 3, gives 1 for both cells. With it, this line prints false, and so does Example 1: the 6 at (2, 7) and the 6 at (3, 4) both get box 2, although they are in boxes 2 and 4.

The original implementation, ValidSudoku.java, is on GitHub.

Complexity

The board always has 81 cells, and each one costs a fixed amount of work.

  • Time: O(1), because the board is always 9 x 9. The two loops visit 81 cells, with three lookups and three writes for each filled one. On an n x n board, the same pass would take O(n²), one step per cell.
  • Space: O(1). The three 9 x 9 tables hold 243 booleans, whatever digits the board has.

The same three notes decide which digits may go in a cell in Sudoku Solver.