# Knight's Tour, refusing to pass move #29, code included, please help.

Printable View

• 08-03-2011, 03:36 AM
ifnotforthecake
Knight's Tour, refusing to pass move #29, code included, please help.
So, my homework is to code a program to simulate a Knight's Tour. It needs to pass all 64 spaces on an 8x8 grid, without passing the same space twice.

but my program seems to not want to pass the 29th move. I've checked everything, but I can't manage to find out where I'm wrong.
Maybe someone could assist me in finding where the problem lies.

Much appreciated!

Code:

```public class KnightsTour {     int grid[][];     boolean finished;     final int Xcord[] = {-1, 1, -1, 1, -2, 2, -2, 2};     final int Ycord[] = {-2, 2, 2, -2, -1, 1, 1, -1};     public static void main(String args[])     {         int totalMoves = 1;         KnightsTour kt = new KnightsTour();         kt.check( 0, 0, totalMoves);         kt.drawGrid();     }         public KnightsTour()     {         grid = new int[8][8];         finished = false;         grid[0][0] = 1;     }         public int check(int x, int y, int totalMoves)     {         for(int i = 0; i < grid.length; i++)         {             if(finished == true)             {                 return totalMoves;             }             else             {                 if(x+Xcord[i]<8 && x+Xcord[i]>=0)                 {                     if(y+Ycord[i]<8 && y+Ycord[i]>=0)                     {                                        if((grid[x+Xcord[i]][y+Ycord[i]])==0)                         {                             grid[x+Xcord[i]][y+Ycord[i]]=-1;                             grid[x+Xcord[i]][y+Ycord[i]]=check(x+Xcord[i],y+Ycord[i], totalMoves + 1);                             finished = true;                         }                     }                    }             }          }         if(totalMoves >= 64 || finished == true)         {             finished = true;             return totalMoves;         }         else         {             return 0;         }        }         public void drawGrid()     {         for(int i = 0; i < grid.length; i++)         {             System.out.println();             for(int j = 0; j < grid.length; j++)             {                 if(grid[j][i] < 10)                 {                     System.out.print(" 0" + grid[j][i]);                 }                 else                 {                     System.out.print(" " + grid[j][i]);                 }             }         }     } }```
• 08-03-2011, 01:30 PM
Norm
Have you tried debugging the code by adding printlns to show the reason why it stops searching before the end?
What values of what variables stops the search?