The following program is designed to move a Knight across a chess board until it has touched all 64 spaces. However, when I run it, it returns a stack overflow error. Any ideas?
public class Knight
{
static int[][] board = new int[8][8];
static int r,c,rmove,cmove, count = 0;
static int Knight = 2; //THIS IS THE COUNTER OF HOW MANY MOVES HE HAS MADE
static int i=0; static int j=0;
public static void main(String[] args)
{
//DRAW THE BOARD AND FILL WITH 0'S
for(r = 0; r<8; r++)
{
for (int c = 0; c<8; c++)
{
board[r][c]= 0;
}
}
r=0;
c=0;
board[r][c]= 1;
tour();
//PRINT THE BOARD WHEN DONE
for(c=0;c<8;c++){
for(r=0;r<8;r++){
System.out.print(board[r][c]);
System.out.print(" ");
}
System.out.print("\n");
}
}
public static int [][] tour(){
move();
if (board[r+rmove][c+cmove] == 0){
board[r+rmove][c+cmove] = Knight;
r = r + rmove;
c = c + cmove;
Knight++;
tour();
}
else if(Knight > 64)
System.out.println("Hes done");
else
tour();
Knight++;
return board;
}
public static void move(){
rmove = (int)(Math.random()*2) +1 ;
if (rmove == 1)
cmove = 2;
else
cmove = 1;
j++;
System.out.print(j + ", ");
int posneg = (int)(Math.random()*4)+1;
switch(posneg){
case 1:
rmove = rmove *-1;
break;
case 2:
cmove = cmove *-1;
break;
case 3:
rmove = rmove * -1;
cmove = cmove * -1;
default:
break;
}
if (r + rmove <0 || r + rmove > 7)
rmove = rmove * -1;
if (c + cmove < 0 || c + cmove > 7)
cmove = cmove * -1;
}
}
public class Knight
{
static int[][] board = new int[8][8];
static int r,c,rmove,cmove, count = 0;
static int Knight = 2; //THIS IS THE COUNTER OF HOW MANY MOVES HE HAS MADE
static int i=0; static int j=0;
public static void main(String[] args)
{
//DRAW THE BOARD AND FILL WITH 0'S
for(r = 0; r<8; r++)
{
for (int c = 0; c<8; c++)
{
board[r][c]= 0;
}
}
r=0;
c=0;
board[r][c]= 1;
tour();
//PRINT THE BOARD WHEN DONE
for(c=0;c<8;c++){
for(r=0;r<8;r++){
System.out.print(board[r][c]);
System.out.print(" ");
}
System.out.print("\n");
}
}
public static int [][] tour(){
move();
if (board[r+rmove][c+cmove] == 0){
board[r+rmove][c+cmove] = Knight;
r = r + rmove;
c = c + cmove;
Knight++;
tour();
}
else if(Knight > 64)
System.out.println("Hes done");
else
tour();
Knight++;
return board;
}
public static void move(){
rmove = (int)(Math.random()*2) +1 ;
if (rmove == 1)
cmove = 2;
else
cmove = 1;
j++;
System.out.print(j + ", ");
int posneg = (int)(Math.random()*4)+1;
switch(posneg){
case 1:
rmove = rmove *-1;
break;
case 2:
cmove = cmove *-1;
break;
case 3:
rmove = rmove * -1;
cmove = cmove * -1;
default:
break;
}
if (r + rmove <0 || r + rmove > 7)
rmove = rmove * -1;
if (c + cmove < 0 || c + cmove > 7)
cmove = cmove * -1;
}
}