Java Backtracking Program · OT67
Sudoku Solver in Java
Find the first empty cell, try each digit that does not clash with its row, column or box, and recurse. If nothing fits later on, undo the digit and try the next one.
Problem Statement
Given a partially filled 9 × 9 grid, with 0 for empty cells, fill every empty cell so that each row, each column and each 3 × 3 box contains the digits 1 to 9 exactly once.
Solve the grid in place and report whether a solution was found. The example puzzle has 45 empty cells.
Input/Output Examples
45 empty cellsOutputsolved: trueExplanation: the full grid is printed and checked.every row, column and boxOutputvalid: trueExplanation: each contains 1 to 9 exactly once.two equal digits in a rowOutputsolved: falseExplanation: the search exhausts every option.Visual Explanation
- First blankcell r0 c01?21 clashes; 2 fits
- Next blankcell r0 c17recurse
- Dead endsome cellno digitundo the last choice backtrack
- Continuetry the next digit at the earlier cell
- Doneall 81 cells filled
Filling cells in a fixed order (row by row) means both programs explore choices in the same order and therefore find the same solution.
Approaches
Both approaches use the same search order. One checks each digit by scanning; the other keeps bitmasks of used digits.
Approach 1: Backtracking With Scans (Recommended)
Idea: for the first empty cell, try digits 1 to 9 that do not appear in the same row, column or box, recursing after each.
- Find the first empty cell, scanning row by row.
- For each digit, check its row, column and box with one loop of 9.
- Place it and recurse; on failure, reset the cell to 0.
- If no empty cell remains, the grid is solved.
Time: O(9e) · Space: O(e). e is the number of empty cells (worst case).
Approach 2: Backtracking With Bitmasks
Idea: keep one 10-bit mask per row, column and box; a digit fits when its bit is clear in all three.
- Build the masks from the given digits.
- Combine the three masks of a cell to see every used digit at once.
- Set the bits when placing a digit and clear them when backtracking.
Time: O(9e) · Space: O(1). Same worst case, but each check is constant time.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Backtracking With Scans (Recommended)
Short and clear; the program also prints the grid and verifies the result.
public class SudokuBacktrack {
// Fill the first empty cell (row by row) with each digit that fits, and undo when stuck
static boolean solve(int[][] g) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (g[r][c] == 0) {
for (int d = 1; d <= 9; d++) {
if (fits(g, r, c, d)) {
g[r][c] = d;
if (solve(g)) {
return true;
}
g[r][c] = 0; // backtrack
}
}
return false; // no digit fits this cell
}
}
}
return true; // no empty cell left
}
private static boolean fits(int[][] g, int r, int c, int d) {
int br = 3 * (r / 3), bc = 3 * (c / 3);
for (int i = 0; i < 9; i++) {
if (g[r][i] == d || g[i][c] == d || g[br + i / 3][bc + i % 3] == d) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] rows = {
"008510436", "509006200", "430000009",
"780100062", "190000080", "060005004",
"850003000", "040027801", "007001940"
};
int[][] g = new int[9][9];
int blanks = 0;
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
g[r][c] = rows[r].charAt(c) - '0';
if (g[r][c] == 0) {
blanks++;
}
}
}
System.out.println("blank cells: " + blanks);
System.out.println("solved: " + solve(g));
for (int[] row : g) {
StringBuilder sb = new StringBuilder();
for (int c = 0; c < 9; c++) {
sb.append(row[c]).append(c == 2 || c == 5 ? " | " : c < 8 ? " " : "");
}
System.out.println(sb);
}
System.out.println("valid: " + isValidSolution(g));
}
static boolean isValidSolution(int[][] g) {
for (int i = 0; i < 9; i++) {
boolean[] row = new boolean[10], col = new boolean[10], box = new boolean[10];
for (int j = 0; j < 9; j++) {
int a = g[i][j], b = g[j][i], c = g[3 * (i / 3) + j / 3][3 * (i % 3) + j % 3];
if (a == 0 || row[a] || col[b] || box[c]) {
return false;
}
row[a] = col[b] = box[c] = true;
}
}
return true;
}
}
blank cells: 45 solved: true 2 7 8 | 5 1 9 | 4 3 6 5 1 9 | 4 3 6 | 2 7 8 4 3 6 | 2 7 8 | 5 1 9 7 8 5 | 1 9 4 | 3 6 2 1 9 4 | 3 6 2 | 7 8 5 3 6 2 | 7 8 5 | 1 9 4 8 5 1 | 9 4 3 | 6 2 7 9 4 3 | 6 2 7 | 8 5 1 6 2 7 | 8 5 1 | 9 4 3 valid: true
Time complexity: O(9e) · Space complexity: O(e).
Approach 2: Backtracking With Bitmasks
Much faster in practice, because checks no longer scan the grid.
public class SudokuBitmask {
private static final int[] rowMask = new int[9], colMask = new int[9], boxMask = new int[9];
// Bit d of a mask is set when digit d is already used, so each check is O(1)
static boolean solve(int[][] g) {
java.util.Arrays.fill(rowMask, 0);
java.util.Arrays.fill(colMask, 0);
java.util.Arrays.fill(boxMask, 0);
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (g[r][c] != 0) {
set(r, c, g[r][c], true);
}
}
}
return fill(g, 0);
}
private static boolean fill(int[][] g, int pos) {
while (pos < 81 && g[pos / 9][pos % 9] != 0) {
pos++; // same row-by-row order as the plain version
}
if (pos == 81) {
return true;
}
int r = pos / 9, c = pos % 9, b = (r / 3) * 3 + c / 3;
int used = rowMask[r] | colMask[c] | boxMask[b];
for (int d = 1; d <= 9; d++) {
if ((used & (1 << d)) == 0) {
g[r][c] = d;
set(r, c, d, true);
if (fill(g, pos + 1)) {
return true;
}
set(r, c, d, false);
g[r][c] = 0;
}
}
return false;
}
private static void set(int r, int c, int d, boolean on) {
int bit = 1 << d, b = (r / 3) * 3 + c / 3;
if (on) {
rowMask[r] |= bit; colMask[c] |= bit; boxMask[b] |= bit;
} else {
rowMask[r] &= ~bit; colMask[c] &= ~bit; boxMask[b] &= ~bit;
}
}
public static void main(String[] args) {
String[] rows = {
"008510436", "509006200", "430000009",
"780100062", "190000080", "060005004",
"850003000", "040027801", "007001940"
};
int[][] g = new int[9][9];
int blanks = 0;
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
g[r][c] = rows[r].charAt(c) - '0';
if (g[r][c] == 0) {
blanks++;
}
}
}
System.out.println("blank cells: " + blanks);
System.out.println("solved: " + solve(g));
for (int[] row : g) {
StringBuilder sb = new StringBuilder();
for (int c = 0; c < 9; c++) {
sb.append(row[c]).append(c == 2 || c == 5 ? " | " : c < 8 ? " " : "");
}
System.out.println(sb);
}
System.out.println("valid: " + isValidSolution(g));
}
static boolean isValidSolution(int[][] g) {
for (int i = 0; i < 9; i++) {
boolean[] row = new boolean[10], col = new boolean[10], box = new boolean[10];
for (int j = 0; j < 9; j++) {
int a = g[i][j], b = g[j][i], c = g[3 * (i / 3) + j / 3][3 * (i % 3) + j % 3];
if (a == 0 || row[a] || col[b] || box[c]) {
return false;
}
row[a] = col[b] = box[c] = true;
}
}
return true;
}
}
blank cells: 45 solved: true 2 7 8 | 5 1 9 | 4 3 6 5 1 9 | 4 3 6 | 2 7 8 4 3 6 | 2 7 8 | 5 1 9 7 8 5 | 1 9 4 | 3 6 2 1 9 4 | 3 6 2 | 7 8 5 3 6 2 | 7 8 5 | 1 9 4 8 5 1 | 9 4 3 | 6 2 7 9 4 3 | 6 2 7 | 8 5 1 6 2 7 | 8 5 1 | 9 4 3 valid: true
Time complexity: O(9e) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Backtracking With Scans | O(9e) | O(e) |
| Backtracking With Bitmasks | O(9e) | O(1) |
Here e is the number of empty cells. The worst case is exponential, but constraint checks prune almost every branch, so typical puzzles solve in milliseconds.
Interview Tips and Recommended Approach
- Compute the box index as
(r / 3) * 3 + c / 3. - Always undo a placement before trying the next digit.
- Mention a key speed-up: choose the empty cell with the fewest possible digits first.
- Validate the input; a grid that breaks the rules from the start can never be solved.
Recommended Approach: Backtracking With Scans
Why: it is the most direct backtracking solution and is easy to verify, which is exactly what interviewers look for.