// Function to print the Sudoku grid
function printGrid(grid) {
for (let row = 0; row < N; row++) {
let rowStr = '';
for (let col = 0; col < N; col++) {
rowStr += grid[row][col] + ' ';
}
console.log(rowStr);
}
}
// Function to solve Sudoku recursively
function solve(r, c, board, submatrixDigits, rowDigits, columnDigits) {
// Base case: If all rows are filled, the Sudoku is solved
if (r === 9) {
return true;
}
// If a row is filled, move to the next row
if (c === 9) {
return solve(r + 1, 0, board, submatrixDigits, rowDigits, columnDigits);
}
// If the cell is empty
if (board[r][c] === 0) {
for (let i = 1; i <= 9; i++) {
const digit = 1 << (i - 1);
// Check if the digit is not present in the same row, column, or submatrix
if (!(submatrixDigits[Math.floor(r / 3)][Math.floor(c / 3)] & digit)
&& !(rowDigits[r] & digit)
&& !(columnDigits[c] & digit)) {
// Set the digit and continue solving
submatrixDigits[Math.floor(r / 3)][Math.floor(c / 3)] |= digit;
rowDigits[r] |= digit;
columnDigits[c] |= digit;
board[r][c] = i;
if (solve(r, c + 1, board, submatrixDigits, rowDigits, columnDigits)) {
return true;
} else {
// Backtrack if the digit doesn't lead to a solution
submatrixDigits[Math.floor(r / 3)][Math.floor(c / 3)] &= ~digit;
rowDigits[r] &= ~digit;
columnDigits[c] &= ~digit;
board[r][c] = 0;
}
}
}
return false;
}
// If the cell is already filled, move to the next cell
return solve(r, c + 1, board, submatrixDigits, rowDigits, columnDigits);
}
// Function to check if Sudoku can be solved
function solveSudoku(board) {
// Initialize arrays to track digits in submatrices, rows, and columns
const submatrixDigits = Array.from({ length: 3 }, () => Array(3).fill(0));
const rowDigits = new Array(9).fill(0);
const columnDigits = new Array(9).fill(0);
// Populate the arrays with initial Sudoku values
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (board[i][j] > 0) {
const value = 1 << (board[i][j] - 1);
submatrixDigits[Math.floor(i / 3)][Math.floor(j / 3)] |= value;
rowDigits[i] |= value;
columnDigits[j] |= value;
}
}
}
// Start solving Sudoku using backtracking
if (solve(0, 0, board, submatrixDigits, rowDigits, columnDigits)) {
return true; // Sudoku solved successfully
} else {
return false; // No solution exists
}
}
// Define the Sudoku grid
const N = 9;
const grid = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]
];
// Solve the Sudoku
if (solveSudoku(grid)) {
// Print the solved Sudoku grid
printGrid(grid);
} else {
console.log("No solution exists");
}