// Solve knight's tour chess puzzle
// See C++htp, exercise ?? for definitions and related discussion.
// bds 11/98
#include <stdlib.h>   // for atoi
#include <iostream.h> // for cout
#include "board.h"    // for Board class

int kt(Board&); // Prototype for the function that solves the puzzle.
extern int showMoves = 0; // Control of display of search steps.
                          // Set in main, used in validMove.

int main(int argc, char* argv[]){
  if (argc < 3) {
    cout << "usage: " 
	 << argv[0] << " m n -- to solve knight tour on m by n board" << endl;
    return 0;
  }
  int m = atoi( argv[1] );
  int n = atoi( argv[2] );
  if (argc > 3) showMoves = atoi( argv[3] );
  Board B = *new Board( m, n );

  int result = kt( B );

  cout << "Best result on " << m << " by " << n << " board ";
  cout << "is " << result << endl;
  // we ought to display the solution!
}  


template <class N> // N can be any type for which '>' is defined. 
inline N max(N a, N b) { return (a > b) ? a : b ; }

// kt( b ) extends the partial solution on b as far as possible
// It returns the number of knights on a maximal extension
// It modifies the board b during it's operation, but in the end it
// leaves b as it was initiallly.

int kt(Board& b) {
  int bestYet = b.last;
  if ( bestYet == b.goal ) return bestYet;
  for (int i = 0; i < 8; i++) 
    if ( b.validMove( i ) ) {
      b.extend( i );
      int score = kt( b ); // recursive call
      if (score == b.goal) return score;
      bestYet = max( bestYet, score );
      b.unextend();
    }
  return bestYet;
}
