Print all Knight 's tour possible from a starting point on NxN chessboard | Stores the 8 possible combinations of moves that the knight can follow ; Function to find if ( i , j ) is a valid cell for the knight to move and it exists within the chessboard ; Stores whether there exist any valid path ; Recursive function to iterate through all the paths that the knight can follow ; Mark the current square of the chessboard ; If the number of visited squares are equal to the total number of sqares ; Prlet the current state of ChessBoard ; Backtrack to the previous move ; Iterate through all the eight possible moves for a knight ; Stores the new position of the knight after a move ; If the new position is a valid position recursively call for the next move ; Backtrack to the previous move ; Driver Code ; If no valid sequence of moves exist
let DirX = [ 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 ] ; let DirY = [ 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 ] ; function isSafe ( i , j , n , Board ) { return i >= 0 && j >= 0 && i < n && j < n && Board [ i ] [ j ] == 0 ; } let isPossible = false ; function knightTour ( ChessBoard , N , x , y , visited = 1 ) { ChessBoard [ x ] [ y ] = visited ; if ( visited == N * N ) { isPossible = true ; for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { document . write ( ChessBoard [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } document . write ( " " ) ; ChessBoard [ x ] [ y ] = 0 ; return ; } for ( let i = 0 ; i < 8 ; i ++ ) { let newX = x + DirX [ i ] ; let newY = y + DirY [ i ] ; if ( isSafe ( newX , newY , N , ChessBoard ) && ! ChessBoard [ newX ] [ newY ] ) { knightTour ( ChessBoard , N , newX , newY , visited + 1 ) ; } } ChessBoard [ x ] [ y ] = 0 ; } let ChessBoard = new Array ( 5 ) . fill ( 0 ) . map ( ( ) => new Array ( 5 ) . fill ( 0 ) ) ; let N = ChessBoard . length ; let X = 1 ; let Y = 1 ; knightTour ( ChessBoard , N , X - 1 , Y - 1 ) ; if ( ! isPossible ) { document . write ( " " ) ; }