class SudokuSolver {
board: number[][];
constructor(board: number[][]) {
this.board = board;
}
isValid(row: number, col: number, num: number): boolean {
// Check row for duplicate
for (let x = 0; x < 9; x++) {
if (this.board[row][x] === num) return false;
}
// Check column for duplicate
for (let y = 0; y < 9; y++) {
if (this.board[y][col] === num) return false;
}
// Check 3x3 box for duplicate
const startRow = Math.floor(row / 3) * 3;
const startCol = Math.floor(col / 3) * 3;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (this.board[startRow + i][startCol + j] === num) return false;
}
}
return true;
}
solve(): boolean {
for (let row = 0; row < 9; row++) {
for (let col = 0; col < 9; col++) {
if (this.board[row][col] === 0) {
for (let num = 1; num <= 9; num++) {
if (this.isValid(row, col, num)) {
this.board[row][col] = num; // place num
if (this.solve()) {
return true; // solved
}
this.board[row][col] = 0; // backtrack
}
}
return false; // no valid number found
}
}
}
return true; // no empty cells left
}
printBoard(): void {
for (let i = 0; i < 9; i++) {
let line = '';
for (let j = 0; j < 9; j++) {
line += this.board[i][j] + (j === 8 ? '' : ' ');
}
console.log(line);
}
}
}
const board = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
];
const solver = new SudokuSolver(board);
if (solver.solve()) {
solver.printBoard();
} else {
console.log('No solution exists');
}