
public class Board {


  private static final int FREE = 0;
  
  private final int size;
  
  private int[][] chessBoard;
  private int first, last;
  private int solution = 0;
  
  
  public Board(int size) {
  
    this.size = size;
    
    chessBoard = new int[size][size];
    
    for (int i=0; i<size; i++) {
      for (int j=0; j<size; j++) {
        chessBoard[i][j] = FREE;
      }
    }
  }
  
  
  public void tryTour(int x, int y,  int first, int last) {
  
    this.first = first;  // soluzioni da "first" a "last"
    this.last = last;
    
    jump( x-1,y-1, 1 );
  }
  
  
  private void jump(int x, int y, int move) {
  
    if ( fair(x,y) ) {
    
      chessBoard[x][y] = move;
    
      if (move == size*size) {
      
        show();
      
      } else if (solution < last) {
      
        jump( x-2,y+1, move+1 );
        jump( x-1,y+2, move+1 );
        jump( x+1,y+2, move+1 );
        jump( x+2,y+1, move+1 );
        jump( x+2,y-1, move+1 );
        jump( x+1,y-2, move+1 );
        jump( x-1,y-2, move+1 );
        jump( x-2,y-1, move+1 );
      }
      chessBoard[x][y] = FREE;
    }
  }
  
  
  private boolean fair(int x, int y) {
  
    return ( (x >= 0) && (x < size) && (y >= 0) &&
             (y < size) && (chessBoard[x][y] == FREE) );
  }
  
  
  private void show() {
  
    solution = solution + 1;
    
    System.out.println( "  solution " + solution );
    
    if ((solution >= first) && (solution <= last)) {
      for (int i=0; i<size; i++) {
        System.out.println();
        System.out.print(" ");
        for (int j=0; j<size; j++) {
          if (chessBoard[i][j] < 10) {
            System.out.print("  "+chessBoard[i][j]);
          } else {
            System.out.print(" "+chessBoard[i][j]);
          }
        }
        System.out.println();
      }
      System.out.println();
    }
  }

}
  
