22
33class OpenKnightTour {
44 constructor ( size ) {
5+ // Constructor to initialize the chessboard and size
56 this . board = new Array ( size ) . fill ( 0 ) . map ( ( ) => new Array ( size ) . fill ( 0 ) )
67 this . size = size
78 }
89
910 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
1112 const moves = [
1213 [ i + 2 , j - 1 ] ,
1314 [ i + 2 , j + 1 ] ,
@@ -19,18 +20,19 @@ class OpenKnightTour {
1920 [ i - 1 , j + 2 ]
2021 ]
2122
23+ // Filter out moves that are within the board boundaries
2224 return moves . filter (
2325 ( [ y , x ] ) => y >= 0 && y < this . size && x >= 0 && x < this . size
2426 )
2527 }
2628
2729 isComplete ( ) {
28- // helper function to check if the board is complete
30+ // Helper function to check if the board is complete
2931 return ! this . board . map ( ( row ) => row . includes ( 0 ) ) . includes ( true )
3032 }
3133
3234 solve ( ) {
33- // function to find the solution for the given board
35+ // Function to find the solution for the given board
3436 for ( let i = 0 ; i < this . size ; i ++ ) {
3537 for ( let j = 0 ; j < this . size ; j ++ ) {
3638 if ( this . solveHelper ( [ i , j ] , 0 ) ) return true
@@ -40,22 +42,23 @@ class OpenKnightTour {
4042 }
4143
4244 solveHelper ( [ i , j ] , curr ) {
43- // helper function for the main computation
45+ // Helper function for the main computation
4446 if ( this . isComplete ( ) ) return true
4547
48+ // Iterate through possible moves and attempt to fill the board
4649 for ( const [ y , x ] of this . getMoves ( [ i , j ] ) ) {
4750 if ( this . board [ y ] [ x ] === 0 ) {
4851 this . board [ y ] [ x ] = curr + 1
4952 if ( this . solveHelper ( [ y , x ] , curr + 1 ) ) return true
50- // backtracking
53+ // Backtracking: If the solution is not found, reset the cell to 0
5154 this . board [ y ] [ x ] = 0
5255 }
5356 }
5457 return false
5558 }
5659
5760 printBoard ( output = ( value ) => console . log ( value ) ) {
58- // utility function to display the board
61+ // Utility function to display the board
5962 for ( const row of this . board ) {
6063 let string = ''
6164 for ( const elem of row ) {
0 commit comments