Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function solveSudoku(board) {
const size = 9;
function isValid(num, row, col) {
// Check if 'num' is not present in the current row, column, and 3x3 grid
for (let i = 0; i < size; i++) {
if (
board[row][i] === num ||
board[i][col] === num ||
board[row - (row % 3) + Math.floor(i / 3)][col - (col % 3) + (i % 3)] === num
) {
return false;
}
}
return true;
}
function solve() {
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if (board[row][col] === 0) {
for (let num = 1; num <= size; num++) {
if (isValid(num, row, col)) {
board[row][col] = num;
if (solve()) {
return true; // If the current configuration leads to a solution
}
// If the current configuration doesn't lead to a solution, backtrack
board[row][col] = 0;
}
}
return false; // If no number can be placed at this cell
}
}
}
return true; // If the entire board is filled
}
if (solve()) {
return board; // Return the solved Sudoku board
} else {
return "No solution exists."; // Return a message if no solution exists
}
}
export {solveSudoku }