File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // Wikipedia: https://en.wikipedia.org/wiki/Knight%27s_tour
2+
3+ class OpenKnightTour {
4+ constructor ( size ) {
5+ this . board = new Array ( size ) . fill ( 0 ) . map ( ( ) => new Array ( size ) . fill ( 0 ) )
6+ this . size = size
7+ }
8+
9+ getMoves ( [ i , j ] ) {
10+ // helper function to get the valid moves of the knight from the current position
11+ const moves = [
12+ [ i + 2 , j - 1 ] ,
13+ [ i + 2 , j + 1 ] ,
14+ [ i - 2 , j - 1 ] ,
15+ [ i - 2 , j + 1 ] ,
16+ [ i + 1 , j - 2 ] ,
17+ [ i + 1 , j + 2 ] ,
18+ [ i - 1 , j - 2 ] ,
19+ [ i - 1 , j + 2 ]
20+ ]
21+
22+ return moves . filter ( ( [ y , x ] ) => y >= 0 && y < this . size && x >= 0 && x < this . size )
23+ }
24+
25+ isComplete ( ) {
26+ // helper function to check if the board is complete
27+ return ! this . board . map ( row => row . includes ( 0 ) ) . includes ( true )
28+ }
29+
30+ solve ( ) {
31+ // function to find the solution for the given board
32+ for ( let i = 0 ; i < this . size ; i ++ ) {
33+ for ( let j = 0 ; j < this . size ; j ++ ) {
34+ if ( this . solveHelper ( [ i , j ] , 0 ) ) return true
35+ }
36+ }
37+ return false
38+ }
39+
40+ solveHelper ( [ i , j ] , curr ) {
41+ // helper function for the main computation
42+ if ( this . isComplete ( ) ) return true
43+
44+ for ( const [ y , x ] of this . getMoves ( [ i , j ] ) ) {
45+ if ( this . board [ y ] [ x ] === 0 ) {
46+ this . board [ y ] [ x ] = curr + 1
47+ if ( this . solveHelper ( [ y , x ] , curr + 1 ) ) return true
48+ // backtracking
49+ this . board [ y ] [ x ] = 0
50+ }
51+ }
52+ return false
53+ }
54+
55+ printBoard ( ) {
56+ // utility function to display the board
57+ for ( const row of this . board ) {
58+ let string = ''
59+ for ( const elem of row ) {
60+ string += elem + '\t'
61+ }
62+ console . log ( string )
63+ }
64+ }
65+ }
66+
67+ function main ( ) {
68+ const board = new OpenKnightTour ( 5 )
69+
70+ board . printBoard ( )
71+ console . log ( '\n' )
72+
73+ board . solve ( )
74+
75+ board . printBoard ( )
76+ }
77+
78+ main ( )
You can’t perform that action at this time.
0 commit comments