
Sponsored
Sponsored
The backtracking approach is a classic method to solve problems like Sudoku that require exploring all configurations to find a valid solution. This involves recursively trying all numbers from 1 to 9 in each cell and verifying if they meet Sudoku rules. If a number fits, move to the next cell. If stuck, backtrack to the previous cell and try a different number. This method ensures all constraints are respected at each step.
Time Complexity: O(9^(N*N)), where N = 9 (the size of the board), as each empty cell has 9 possibilities.
Space Complexity: O(N*N) for the recursion stack.
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 bool isValid(vector<vector<char>>& board, int row, int col, char c) {
7 for (int i = 0; i < 9; i++) {
8 if (board[i][col] == c || board[row][i] == c ||
9 board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
10 return false;
11 }
12 }
13 return true;
14 }
15 bool solve(vector<vector<char>>& board) {
16 for (int i = 0; i < board.size(); i++) {
17 for (int j = 0; j < board[0].size(); j++) {
18 if (board[i][j] == '.') {
19 for (char c = '1'; c <= '9'; c++) {
20 if (isValid(board, i, j, c)) {
21 board[i][j] = c;
22 if (solve(board)) return true;
23 board[i][j] = '.';
24 }
25 }
26 return false;
27 }
28 }
29 }
30 return true;
31 }
32 void solveSudoku(vector<vector<char>>& board) {
33 solve(board);
34 }
35};This C++ solution also uses a backtracking approach. It checks for valid numbers using the isValid method and employs recursion in the solve function to fill the board step by step, backtracking when necessary.
This approach enhances the basic backtracking method by introducing constraint propagation. Before choosing a number for a cell, it checks constraints upfront, reducing unnecessary exploration by propagating constraints once a number is filled. This technique decreases the number of options that need to be tried, thereby optimizing the backtracking process.
Time Complexity: Expected better than O(9^(N*N)), depending on effectiveness of constraint propagation reducing possible combinations.
Space Complexity: O(N*N), influenced by recursion.
1class Solution:
2 def solveSudoku(self, board: List[List
This Python solution incorporates constraint propagation into the backtracking method. It attempts to minimize choices by evaluating constraints before any number is placed, helping to reduce the branching factor in the search tree. If a valid scenario is found using propagation, it progresses further in solving the Sudoku.