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[][]'1''9''.'truefalse
- no digit appears twice in the same row;
- no digit appears twice in the same column;
- no digit appears twice in the same 3 x 3 box. The board is split into nine such boxes.
Only the digits already on the board are checked. A board can be valid even if it has no solution.
Example 1
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
Output: false
Explanation: the top-left 3 x 3 box now has two 8s.
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.
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]inRow[r][d]rd + 1inColinBox'1'char'1''9'ch - '1''1''9'
Finding a cell's box
Which box is cell (r, c) in? Dividing by 3 answers it. When Java divides one intr / 3c / 3
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
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
Java Solution
The method isValidSudoku
- First, create the three tables of notes,
,inRow andinCol , each ainBox . Java fills newboolean[9][9] arrays withboolean , so every note starts empty.false - Visit every cell with two loops, one inside the other. The outer loop moves
over the rows, and the inner loop movesr over the columns. Read the cell intoc , and skip it if it isch .'.' - Turn the digit into an index with
, and work out the cell's box withd = ch - '1' .box = (r / 3) * 3 + c / 3 - If
,inRow[r][d] orinCol[c][d] is already true, the digit repeats, so returninBox[box][d] .false - Otherwise set all three notes to true and go on. When both loops finish without a repeat, return
.true
The main
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:
true
false
true
false
false
true
Example 1 prints truefalsetrue
The two falseinRowinCol
The last line, truer / 3 + c / 3false
The original implementation,
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