forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku-solver.js
86 lines (83 loc) · 2.21 KB
/
sudoku-solver.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const UNASSIGNED = 0;
/* Returns a boolean which indicates whether any assigned entry
in the specified row matches the given number. */
function usedInRow(grid, row, num) {
for (let col = 0; col < grid.length; col++) {
if (grid[row][col] === num) {
return true;
}
}
return false;
}
/* Returns a boolean which indicates whether any assigned entry
in the specified column matches the given number. */
function usedInCol(grid, col, num) {
for (let row = 0; row < grid.length; row++) {
if (grid[row][col] === num) {
return true;
}
}
return false;
}
/* Returns a boolean which indicates whether any assigned entry
within the specified 3x3 box matches the given number. */
function usedInBox(grid, boxStartRow, boxStartCol, num) {
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
if (grid[row + boxStartRow][col + boxStartCol] === num) {
return true;
}
}
}
return false;
}
function isSafe(grid, row, col, num) {
/* Check if 'num' is not already placed in current row,
current column and current 3x3 box */
return (
!usedInRow(grid, row, num) &&
!usedInCol(grid, col, num) &&
!usedInBox(grid, row - (row % 3), col - (col % 3), num)
);
}
function solveSudoku(grid) {
let row = 0;
let col = 0;
let checkBlankSpaces = false;
// If there is no unassigned location, we are done
for (row = 0; row < grid.length; row++) {
for (col = 0; col < grid[row].length; col++) {
if (grid[row][col] === UNASSIGNED) {
checkBlankSpaces = true;
break;
}
}
if (checkBlankSpaces === true) {
break;
}
}
if (checkBlankSpaces === false) {
return true;
} // success!
// consider digits 1 to 9
for (let num = 1; num <= 9; num++) {
// if looks promising
if (isSafe(grid, row, col, num)) {
// make tentative assignment
grid[row][col] = num;
// return, if success, yay!
if (solveSudoku(grid)) {
return true;
}
// failure, unmake & try again
grid[row][col] = UNASSIGNED;
}
}
return false;
}
export function sudokuSolver(grid) {
if (solveSudoku(grid) === true) {
return grid;
}
return 'NO SOLUTION EXISTS!';
}