1. Linear Scan Validation Backtracking
Intuition
Iterate across all 81 cells. If board[i][j] == '.', try '1' to '9'. Function isValid(board, row, col, c) checks if c appears in row, in col, or in the 3x3 block 3 * (row / 3) + i / 3 and 3 * (col / 3) + i % 3.
Algorithm
- Step 1: Fill all empty cells with random digits 1 to 9.
- Step 2: Validate the entire 9x9 board across all 9 rows, 9 columns, and 9 3x3 sub-boxes.
- Step 3: If valid, return board; otherwise try next configuration.
#include <iostream>#include <vector> class Solution {public: bool isValid(const std::vector<std::vector<char>>& board, int row, int col, char c) { for (int i = 0; i < 9; i++) { if (board[row][i] == c) return false; if (board[i][col] == c) return false; if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; } return true; } bool solve(std::vector<std::vector<char>>& board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { for (char c = '1'; c <= '9'; c++) { if (isValid(board, i, j, c)) { board[i][j] = c; if (solve(board)) return true; board[i][j] = '.'; } } return false; } } } return true; } void solveSudoku(std::vector<std::vector<char>>& board) { solve(board); }}; int main() { Solution solver; std::vector<std::vector<char>> board = { {'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'} }; solver.solveSudoku(board); std::cout << "Solved Sudoku Board:\n"; for (const auto& row : board) { for (char c : row) std::cout << c << " "; std::cout << "\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(9^m * 9)— m empty cells, testing up to 9 digits each with O(9) validation checks. - Space complexity:
O(1) recursion depth bounded by 81— Recursion depth is at most 81 frames.