I have to implement Warnsdorff's Rule via an algorithm given to me by my professor. I've gotten it to work however one thing that I can't get to work is for the ending point to be one "knight's move" away from the starting point. This is my code so far.
// Project1_KnightsTour.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Initializations
int BOARD[8][8] = {0}; //Tracks which squares have been touched and in what order
int KTMOV1[8] = {-2,-1,1,2,2,1,-1,-2}; //8 possible moves from current location (I)
int KTMOV2[8] = {1,2,2,1,-1,-2,-2,-1}; //8 possible moves from current location (J)
int NEXTI[8] = {0}; //Possible next I coordinate
int NEXTJ[8] = {0}; //Possible next J coordinate
int EXITS[8] = {0}; //How many exits does each possible next square have
int I,J,K,L; //I,J are position of knight
int i,j; //Iterators for loops
int min=0; //Saves pos. of next square from which there are the least # of possible exits
int NPOS; //Tracks # of possible next squares that knight can move to
//Read starting location
cout << "Indicate starting position (I,J)\nI = ";
cin >> I;
cout << "J = ";
cin >> J;
//Subtract 1 from I and J for array index format
I -= 1;
J -= 1;
//Set starting location
BOARD[I][J] = 1;
//Top Loop
for(int M=2; M<65; M++){
NPOS = 0;
//////////
if(M==9) ;
//////////
//Form list of possibilities for next square
for(i=0; i<8; i++){
//If next square is ON the board and hasn't been touched yet, store it as a possibility
if(I+KTMOV1[i]<8 && I+KTMOV1[i]>-1 && J+KTMOV2[i]<8 && J+KTMOV2[i]>-1
&& BOARD[I+KTMOV1[i]][J+KTMOV2[i]] == 0){
NEXTI[NPOS] = I+KTMOV1[i];
NEXTJ[NPOS] = J+KTMOV2[i];
NPOS++;
}
}
//Test special cases
if(NPOS==0) cout << "Failure, no more possible moves (Turn " << M << ")\n";
if(NPOS==1) min = 0;
//Find next square with min exits (only if > 1 possibilities)
for(L=0; L<NPOS && NPOS>1; L++){
for(j=0; j<8; j++){
//Again, Only store as possibility if next space is ON the board and untouched
if(NEXTI[L]+KTMOV1[j]<8 && NEXTI[L]+KTMOV1[j]>-1
&& NEXTJ[L]+KTMOV2[j]<8 && NEXTJ[L]+KTMOV2[j]>-1
&& BOARD[NEXTI[L]+KTMOV1[j]][NEXTJ[L]+KTMOV2[j]]==0)
EXITS[L]++; //For each possibility keep track of how many exits
}
if(EXITS[L]<EXITS[min] || L==0) //always set min on the first loop
min = L; //Save which possibility has the least exits
}
//Clear EXITS for next use
for(i=0; i<8; i++)
EXITS[i] = 0;
//Move the knight: set new position I, J. And save turn number to the square on BOARD.
I = NEXTI[min];
J = NEXTJ[min];
BOARD[I][J] = M;
}
//Print the board
for(i=0; i<8; i++){
for(j=0; j<8; j++)
cout << BOARD[i][j] << "\t";
cout << endl;
}
return 0;
}