1
1
class Sudoku {
2
- // Sudoku Class to hold the board and related functions
3
2
constructor ( board ) {
4
3
this . board = board
4
+ this . solutionFound = false
5
5
}
6
6
7
7
findEmptyCell ( ) {
8
- // Find a empty cell in the board (returns [-1, -1] if all cells are filled)
9
8
for ( let i = 0 ; i < 9 ; i ++ ) {
10
9
for ( let j = 0 ; j < 9 ; j ++ ) {
11
10
if ( this . board [ i ] [ j ] === 0 ) return [ i , j ]
12
11
}
13
12
}
14
- return [ - 1 , - 1 ]
13
+ const noEmptyCell = [ - 1 , - 1 ]
14
+ return noEmptyCell
15
15
}
16
16
17
17
check ( [ y , x ] , value ) {
@@ -41,13 +41,17 @@ class Sudoku {
41
41
solve ( ) {
42
42
const [ y , x ] = this . findEmptyCell ( )
43
43
44
- // checking if the board is complete
45
- if ( y === - 1 && x === - 1 ) return true
44
+ const boardIsComplete = y === - 1 && x === - 1
45
+ if ( boardIsComplete ) {
46
+ this . printBoard ( )
47
+ this . solutionFound = true
48
+ return true
49
+ }
46
50
47
51
for ( let val = 1 ; val < 10 ; val ++ ) {
48
52
if ( this . check ( [ y , x ] , val ) ) {
49
53
this . board [ y ] [ x ] = val
50
- if ( this . solve ( ) ) return true
54
+ this . solve ( )
51
55
// backtracking if the board cannot be solved using current configuration
52
56
this . board [ y ] [ x ] = 0
53
57
}
@@ -61,7 +65,6 @@ class Sudoku {
61
65
}
62
66
63
67
printBoard ( ) {
64
- // helper function to display board
65
68
for ( let i = 0 ; i < 9 ; i ++ ) {
66
69
if ( i % 3 === 0 && i !== 0 ) console . log ( '- - - - - - - - - - - -' )
67
70
console . log (
@@ -73,7 +76,6 @@ class Sudoku {
73
76
}
74
77
75
78
function main ( ) {
76
- // main function with an example
77
79
const sudokuBoard = new Sudoku ( [
78
80
[ 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 ] ,
79
81
[ 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ,
@@ -85,13 +87,10 @@ function main () {
85
87
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 ] ,
86
88
[ 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 ]
87
89
] )
88
-
89
- sudokuBoard . printBoard ( )
90
-
91
- console . log ( '\n' )
92
90
sudokuBoard . solve ( )
93
91
94
- sudokuBoard . printBoard ( )
92
+ // > sudokuBoard.solutionFound
93
+ // true
95
94
}
96
95
97
96
main ( )
0 commit comments