2
2
3
3
class OpenKnightTour {
4
4
constructor ( size ) {
5
+ // Constructor to initialize the chessboard and size
5
6
this . board = new Array ( size ) . fill ( 0 ) . map ( ( ) => new Array ( size ) . fill ( 0 ) )
6
7
this . size = size
7
8
}
8
9
9
10
getMoves ( [ i , j ] ) {
10
- // helper function to get the valid moves of the knight from the current position
11
+ // Helper function to get the valid moves of the knight from the current position
11
12
const moves = [
12
13
[ i + 2 , j - 1 ] ,
13
14
[ i + 2 , j + 1 ] ,
@@ -19,18 +20,19 @@ class OpenKnightTour {
19
20
[ i - 1 , j + 2 ]
20
21
]
21
22
23
+ // Filter out moves that are within the board boundaries
22
24
return moves . filter (
23
25
( [ y , x ] ) => y >= 0 && y < this . size && x >= 0 && x < this . size
24
26
)
25
27
}
26
28
27
29
isComplete ( ) {
28
- // helper function to check if the board is complete
30
+ // Helper function to check if the board is complete
29
31
return ! this . board . map ( ( row ) => row . includes ( 0 ) ) . includes ( true )
30
32
}
31
33
32
34
solve ( ) {
33
- // function to find the solution for the given board
35
+ // Function to find the solution for the given board
34
36
for ( let i = 0 ; i < this . size ; i ++ ) {
35
37
for ( let j = 0 ; j < this . size ; j ++ ) {
36
38
if ( this . solveHelper ( [ i , j ] , 0 ) ) return true
@@ -40,22 +42,23 @@ class OpenKnightTour {
40
42
}
41
43
42
44
solveHelper ( [ i , j ] , curr ) {
43
- // helper function for the main computation
45
+ // Helper function for the main computation
44
46
if ( this . isComplete ( ) ) return true
45
47
48
+ // Iterate through possible moves and attempt to fill the board
46
49
for ( const [ y , x ] of this . getMoves ( [ i , j ] ) ) {
47
50
if ( this . board [ y ] [ x ] === 0 ) {
48
51
this . board [ y ] [ x ] = curr + 1
49
52
if ( this . solveHelper ( [ y , x ] , curr + 1 ) ) return true
50
- // backtracking
53
+ // Backtracking: If the solution is not found, reset the cell to 0
51
54
this . board [ y ] [ x ] = 0
52
55
}
53
56
}
54
57
return false
55
58
}
56
59
57
60
printBoard ( output = ( value ) => console . log ( value ) ) {
58
- // utility function to display the board
61
+ // Utility function to display the board
59
62
for ( const row of this . board ) {
60
63
let string = ''
61
64
for ( const elem of row ) {
0 commit comments