Sudoku Solver in C++ is a popular puzzle that requires filling a 9×9 grid so that each row, column, and 3×3 subgrid contains all digits from 1 to 9 without repetition. This blog will walk through an efficient backtracking approach to sudoku solver algorithm.
What’s Sudoku Solver in C++ algorithm?
The Sudoku Solver algorithm uses backtracking, which systematically explores all possible placements for a number in the grid. If a valid placement is found, the algorithm moves forward; otherwise, it backtracks to try another possibility.
The steps for Solving Sudoku Using C++:
- Find an Empty Cell: Search for a cell containing
0
. - Check for Validity: Try numbers
1-9
and check if placing a number is valid according to Sudoku rules. - Recursive Backtracking: If a valid number is found, place it and recursively solve the rest of the board.
- Undo and Try Another Number: If no solution exists for the current number, reset the cell and try another number.
- Print the Solution: If the entire board is filled correctly, print the solution.
Sudoku Solver in C++ Source Code Implementation
#include <iostream> bool isValid(int board[9][9], int row, int col, int num) { for (int i = 0; i < 9; i++) { if (board[row][i] == num || board[i][col] == num || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num) return false; } return true; } void printBoard(int board[9][9]) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { std::cout << board[row][col] << " "; } std::cout << std::endl; } } void sudokuSolver(int board[9][9]) { int row, col; for (row = 0; row < 9; row++) { for (col = 0; col < 9; col++) { if (board[row][col] == 0) { for (int num = 1; num <= 9; num++) { if (isValid(board, row, col, num)) { board[row][col] = num; sudokuSolver(board); board[row][col] = 0; // Backtrack } } return; } } } printBoard(board); } int main() { int board[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 5, 0, 0, 0, 0, 8, 0, 1}, {0, 0, 0, 3, 2, 4, 9, 0, 0}, {0, 7, 0, 9, 0, 0, 4, 3, 0}, {2, 0, 0, 4, 0, 6, 0, 0, 7}, {0, 8, 4, 0, 0, 2, 0, 9, 0}, {0, 0, 6, 8, 5, 3, 0, 0, 0}, {9, 0, 8, 0, 0, 0, 0, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0} }; sudokuSolver(board); return 0; }
Output
The program prints a valid solved Sudoku board when executed.
Complexity Analysis
- Time Complexity: The worst-case complexity is O(9^(N*N)), where
N = 9
. However, optimizations like constraint propagation can improve performance. - Space Complexity: O(1) since we use the board itself without extra memory.
Conclusion
This C++ program successfully solves Solving Sudoku using C++ using a backtracking approach. Though efficient for small grids, more advanced techniques like constraint programming and heuristic search can further enhance performance for larger puzzles.
Thanks for visiting codehelping.com, for more coding projects and resources.