|
| 1 | +function knightTour(x, y, moveNum) { |
| 2 | + if (moveNum === N*N) { |
| 3 | + return true; |
| 4 | + } |
| 5 | + |
| 6 | + for (var i = 0; i < 8; i++) { |
| 7 | + var nextX = x + X[i]; |
| 8 | + var nextY = y + Y[i]; |
| 9 | + |
| 10 | + posTracer._notify ( 0, nextX)._wait (); |
| 11 | + posTracer._notify ( 1, nextY)._wait (); |
| 12 | + posTracer._denotify (0); |
| 13 | + posTracer._denotify (1); |
| 14 | + /* |
| 15 | + Check if knight is still in the board |
| 16 | + Check that knight does not visit an already visited square |
| 17 | + */ |
| 18 | + if (nextX>=0 && nextX<N && nextY>=0 && nextY<N && board[nextX][nextY]===-1) { |
| 19 | + board[nextX][nextY] = moveNum; |
| 20 | + |
| 21 | + logTracer._print ('Move to ' + nextX + ',' + nextY); |
| 22 | + boardTracer._notify ( nextX, nextY, moveNum)._wait(); |
| 23 | + boardTracer._denotify( nextX, nextY); |
| 24 | + boardTracer._select ( nextX, nextY); |
| 25 | + |
| 26 | + var nextMoveNum = moveNum + 1; |
| 27 | + if ( knightTour (nextX,nextY, nextMoveNum) === true) { |
| 28 | + return true; |
| 29 | + } else { |
| 30 | + logTracer._print ('No place to move from ' + nextX + ',' +nextY + ': Backtrack'); |
| 31 | + board[nextX][nextY] = -1; // backtrack |
| 32 | + boardTracer._notify ( nextX, nextY, -1)._wait(); |
| 33 | + boardTracer._denotify( nextX, nextY); |
| 34 | + boardTracer._deselect( nextX, nextY); |
| 35 | + } |
| 36 | + } else { |
| 37 | + logTracer._print (nextX + ',' + nextY + ' is not a valid move'); |
| 38 | + } |
| 39 | + } |
| 40 | + return false; |
| 41 | +} |
| 42 | + |
| 43 | +board[0][0] = 0; // start from this position |
| 44 | +pos[0] = 0; |
| 45 | +pos[0] = 0; |
| 46 | + |
| 47 | +boardTracer._notify ( 0, 0, 0)._wait(); |
| 48 | +posTracer._notify ( 0, 0)._wait (); |
| 49 | +posTracer._notify ( 1, 0)._wait (); |
| 50 | +boardTracer._denotify( 0, 0); |
| 51 | +boardTracer._denotify( 0, 0); |
| 52 | +posTracer._denotify (0); |
| 53 | +posTracer._denotify (1); |
| 54 | + |
| 55 | +if (knightTour ( 0, 0, 1) === false ) { |
| 56 | + logTracer._print ('Solution does not exist'); |
| 57 | +} else { |
| 58 | + logTracer._print ('Solution found'); |
| 59 | +} |
0 commit comments