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,19 @@ 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
+ if ( this . solve ( ) ) {
55
+ return true
56
+ }
51
57
// backtracking if the board cannot be solved using current configuration
52
58
this . board [ y ] [ x ] = 0
53
59
}
@@ -61,7 +67,6 @@ class Sudoku {
61
67
}
62
68
63
69
printBoard ( ) {
64
- // helper function to display board
65
70
for ( let i = 0 ; i < 9 ; i ++ ) {
66
71
if ( i % 3 === 0 && i !== 0 ) console . log ( '- - - - - - - - - - - -' )
67
72
console . log (
@@ -73,7 +78,6 @@ class Sudoku {
73
78
}
74
79
75
80
function main ( ) {
76
- // main function with an example
77
81
const sudokuBoard = new Sudoku ( [
78
82
[ 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 ] ,
79
83
[ 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ,
@@ -85,13 +89,10 @@ function main () {
85
89
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 ] ,
86
90
[ 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 ]
87
91
] )
88
-
89
- sudokuBoard . printBoard ( )
90
-
91
- console . log ( '\n' )
92
92
sudokuBoard . solve ( )
93
93
94
- sudokuBoard . printBoard ( )
94
+ // > sudokuBoard.solutionFound
95
+ // true
95
96
}
96
97
97
98
main ( )
0 commit comments