A simple Sudoku solver written in C++17 using a classic backtracking algorithm.
The project is structured with a clear separation between:
- Sudoku: board representation, parsing, and printing
- Solver: solving logic and solvability checking
- Solves standard 9×9 Sudoku puzzles
- Input as an 81-character string (
'0'= empty cell) - Pretty console output
- Input validation with exceptions
- Clean object-oriented design
- No global variables
Input:
000030290
009000007
200008301
080500400
600000009
004007020
407100006
900000700
023040000
Output:
+-------+-------+-------+
| 7 8 4 | 1 3 6 | 2 9 5 |
| 3 5 9 | 2 4 8 | 1 6 7 |
| 2 6 1 | 9 5 7 | 8 4 3 |
+-------+-------+-------+
| 8 3 2 | 5 9 1 | 4 7 6 |
| 6 7 5 | 4 8 2 | 3 1 9 |
| 4 9 1 | 7 6 3 | 5 2 8 |
+-------+-------+-------+
| 5 4 7 | 3 1 9 | 6 8 2 |
| 9 2 8 | 6 7 4 | 5 3 1 |
| 1 6 3 | 8 2 5 | 9 7 4 |
+-------+-------+-------+
- C++17 compatible compiler (e.g. g++)
g++ main.cpp Sudoku.cpp Solver.cpp -std=c++17 -Wall -Wextra -o sudoku./sudokuEdit main.cpp and provide a Sudoku puzzle as an 81-character string:
const std::string sudokuString =
"000030290"
"009000007"
"200008301"
"080500400"
"600000009"
"004007020"
"407100006"
"900000700"
"023040000";Rules:
'0'represents an empty cell- Digits
'1'–'9'represent fixed values - The string must contain exactly 81 characters
- Stores the board as
std::array<int, 81> - Parses input from an 81-character string (
fromString) - Provides accessors (
at,setAt) - Prints the board in a human-readable format
- Contains no solving logic
- Implements a recursive backtracking algorithm
- Computes empty positions once and reuses them during recursion
- Provides:
solve(Sudoku&)(modifies the board)isSolvable(const Sudoku&)(checks solvability by solving a copy)
Invalid input throws std::invalid_argument:
- Sudoku string must be exactly 81 characters
- Only digits
'0'–'9'are allowed
Example:
try {
Sudoku s("invalid_input");
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << '\n';
}MIT License. See 'LICENSE' for details.