Skip to content
Java project #19Advanced

Sudoku Solver

Solve any Sudoku in milliseconds with bit-mask constraint propagation and minimum-remaining-values backtracking, and prove whether the solution is unique.

Estimated time
~7 hours to build
Files
5 files · 383 lines
Technologies
Java 21, Bit manipulation (Integer.bitCount, numberOfTrailingZeros), Recursion

Introduction

A naive backtracking solver tries digits cell by cell and can take millions of steps on hard puzzles. This solver keeps, for every row, column and box, a 9-bit mask of used digits, fills every forced cell (naked singles) before guessing, and always guesses in the cell with the fewest options. Hard 17-clue puzzles then need only a couple of thousand guesses.

Problem statement

Read several puzzles (81 digits with 0 or . for blanks, optionally titled with # lines and spread over several lines). Reject puzzles with the wrong number of cells or givens that already break the rules, naming the offending cell. Solve each valid puzzle, print it in a 3×3 grid, report whether the solution is unique (searching for a second solution), whether no solution exists, and how many guesses were needed.

Objectives

  • Represent constraints with bit masks and bit operations
  • Combine constraint propagation with backtracking
  • Use the minimum-remaining-values heuristic
  • Count solutions to test uniqueness

Features

  • Flexible puzzle input with titles
  • Validation of givens with clear errors
  • Uniqueness detection (stops at two solutions)
  • Guess counts that show the effect of propagation

Concepts demonstrated

  • Backtracking
  • Constraint propagation
  • Heuristics (MRV)
  • Bit masks
  • Undoing state

System architecture

Sudoku stores 81 cells and three arrays of masks. candidates(i) is the complement of the row, column and box masks. search first loops over the grid filling cells with exactly one candidate (recording them so they can be undone), then picks the empty cell with the fewest candidates and tries each digit recursively. When no empty cell remains a solution is counted, and the first solution is copied out. Every placement made during a branch is removed before returning, so the grid is restored exactly.

Folder structure

TextProject tree
sudoku-solver/
├── README.md
├── src/Main.java
├── src/Sudoku.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

54 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Sudoku Solver — reads puzzles separated by blank lines (or one 81-character line each),
* validates them, solves them with constraint propagation plus backtracking, reports whether
* the solution is unique and how many guesses were needed.
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<String> puzzles = new ArrayList<>();
List<String> names = new ArrayList<>();
StringBuilder current = new StringBuilder();
String name = null;
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (line.startsWith("#")) {
if (!current.isEmpty()) { puzzles.add(current.toString()); names.add(name); current.setLength(0); }
name = line.substring(1).trim();
} else if (line.isEmpty()) {
if (!current.isEmpty()) { puzzles.add(current.toString()); names.add(name); current.setLength(0); name = null; }
} else {
current.append(line);
}
}
if (!current.isEmpty()) { puzzles.add(current.toString()); names.add(name); }
int solved = 0;
for (int i = 0; i < puzzles.size(); i++) {
String title = names.get(i) == null ? "Puzzle " + (i + 1) : names.get(i);
System.out.println("=== " + title + " ===");
try {
Sudoku s = Sudoku.parse(puzzles.get(i));
System.out.println(s.givens() + " givens");
int count = s.solve(2);
if (count == 0) {
System.out.println("No solution exists.");
} else {
System.out.print(s);
System.out.println(count == 1 ? "Unique solution." : "Solved, but the puzzle has more than one solution.");
System.out.println("Guesses needed: " + s.guesses());
solved++;
}
} catch (IllegalArgumentException e) {
System.out.println("Invalid puzzle: " + e.getMessage());
}
System.out.println();
}
System.out.println(solved + " of " + puzzles.size() + " puzzle(s) solved.");
}
}

What each file does

src/Sudoku.java
Parsing and validation, bit-mask bookkeeping, the propagate-then-branch search and grid printing.
src/Main.java
Reads titled puzzles, solves each and reports uniqueness and guesses.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Easy (solved by propagation alone) ===
30 givens
5 3 4 | 6 7 8 | 9 1 2
6 7 2 | 1 9 5 | 3 4 8
1 9 8 | 3 4 2 | 5 6 7
------+-------+------
8 5 9 | 7 6 1 | 4 2 3
4 2 6 | 8 5 3 | 7 9 1
7 1 3 | 9 2 4 | 8 5 6
------+-------+------
9 6 1 | 5 3 7 | 2 8 4
2 8 7 | 4 1 9 | 6 3 5
3 4 5 | 2 8 6 | 1 7 9
Unique solution.
Guesses needed: 0
=== Hard (17 givens) ===
17 givens
6 9 3 | 7 8 4 | 5 1 2
4 8 7 | 5 1 2 | 9 3 6
1 2 5 | 9 6 3 | 8 7 4
------+-------+------
9 3 2 | 6 5 1 | 4 8 7
5 6 8 | 2 4 7 | 3 9 1
7 4 1 | 3 9 8 | 6 2 5
------+-------+------
3 1 9 | 4 7 5 | 2 6 8
8 5 6 | 1 2 9 | 7 4 3
2 7 4 | 8 3 6 | 1 5 9
Unique solution.
Guesses needed: 1918
=== Not unique ===
0 givens
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | 1 2 3
7 8 9 | 1 2 3 | 4 5 6
------+-------+------
2 3 1 | 6 7 4 | 8 9 5
8 7 5 | 9 1 2 | 3 6 4
6 9 4 | 5 3 8 | 2 1 7
------+-------+------
3 1 7 | 2 6 5 | 9 4 8
5 4 2 | 8 9 7 | 6 3 1
9 6 8 | 3 4 1 | 5 7 2
Solved, but the puzzle has more than one solution.
Guesses needed: 48
=== Contradiction in the givens ===
Invalid puzzle: digit 5 at row 1, column 2 breaks the rules
=== Unsolvable but legal ===
9 givens
No solution exists.
=== Too short ===
Invalid puzzle: a puzzle needs 81 cells, found 5
3 of 6 puzzle(s) solved.
Input
# Easy (solved by propagation alone)
530070000
600195000
098000060
800060003
400803001
700020006
060000280
000419005
000080079

# Hard (17 givens)
000000010400000000020000000000050407008000300001090000300400200050100000000806000

# Not unique
000000000000000000000000000000000000000000000000000000000000000000000000000000000

# Contradiction in the givens
553070000600195000098000060800060003400803001700020006060000280000419005000080079

# Unsolvable but legal
123456780000000009000000000000000000000000000000000000000000000000000000000000000

# Too short
12345

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • The easy puzzle is solved by propagation alone (0 guesses).
  • The 17-clue puzzle has a unique solution found with 1,918 guesses.
  • An empty grid is reported as having more than one solution; contradictory and unsolvable puzzles are recognised.

Common errors

The solver is extremely slow on hard puzzles

Propagate forced cells and branch on the cell with the fewest candidates instead of the first empty cell.

The grid is corrupted after a failed branch

Undo every cell filled during that branch — including the ones filled by propagation.

Possible improvements

  • Add hidden-single propagation (a digit with only one place in a unit)
  • Generate new puzzles with a unique solution
  • Explain the solution step by step for learners

Additional challenges

  1. 1Solve 16×16 Sudoku with the same code.
  2. 2Measure guesses with and without MRV.
  3. 3Solve the puzzle as an exact-cover problem with Dancing Links.

Built and tested it yourself? Mark it to update your dashboard.