I'm trying to complete the good old Knight's tour (Knight piece must touch every square on board without touching a square twice.
My code goes all the way to the point where the knight is at a dead end, and I need to revisit the last stack... How do you get to the last stack? I thought I was supposed subtract one from my counter and call the method again. I can get to the last stack, and my variables will be reset to that stack right? How to do that? Is there a good tutorial somewhere? (I've looked).
Any help at all would be great. I've been working on this for 2 days now.
import static java.lang.System.out;
import java.util.Scanner;
public class knightsTour {
Scanner myScanner = new Scanner (System.in);
int cols = 8;
int rows = 8;
int [] rowMoves = {-2,-2, 1, 1, 2, 2, 1,-1};
int [] colMoves = {-1, 1,-2, 2, 1,-1,-2,-2};
int grid [] [] = new int [rows] [cols];
int myRow = 0;
int myCol = 0;
int moveCounter = 0;
int moveOption = 0;
public static void main(String[] args) {
knightsTour k = new knightsTour();
k.grid [0] [0] = 1;
int moveOption = 0;
if (k.isClear()){
out.println ("Done done");
}
}
public boolean isClear (){
//out.println ("Move Count in moveoption Array "+moveOption);
while (moveOption < 8){
int possRow = (myRow + rowMoves[moveOption]);
int possCol = (myCol + colMoves[moveOption]);
// out.println ("Poss row is "+possRow);
// out.println ("Poss col is "+possCol);
if (possRow < rows && possRow > 0 && possCol < cols && possCol > 0 && grid[possRow][possCol] != 1){
myRow = possRow;
myCol = possCol;
moveCounter++;
grid[myRow][myCol] = 1;
out.println ("My new Row is "+ myRow+" my Col is "+myCol+" Move Number "+moveCounter);
moveOption=0;
return (isClear ());
}
else{
moveOption++;
//out.println("adding to move option");
}
}
out.println ("reducing move counter"); //Gets here if knight is at dead end.
moveCounter--; //Here is where I need to backtrack
int blank = myScanner.nextInt(); //pause
return (isClear ());
}
}