-3

I am attempting to complete the infamous "Knights tour" Where the knight must move around the entirety of a chess board until it has no more options or completes the board. I am getting unwanted out of bounds errors on my "movement" code and can't figure out the issue. All help is appreciated!

import java.util.*;
public class Tour {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[][] board = new int[8][8];

    int rowpos = 1, vertpos = 1;
    board[0][0] =1;
    Random rand = new Random();
    int count = 1;
    for (int v=1; v<0;count++){

     int gen = rand.nextInt(8);

    if (gen == 0 && board[rowpos + 1][vertpos + 2] == 0){
        rowpos = rowpos + 1;
        vertpos = vertpos +2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 1 && board[rowpos - 1][vertpos - 2] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos -2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 2 && board[rowpos - 1][vertpos + 2] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos +2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 3 && board[rowpos + 1][vertpos - 2] == 0){
        rowpos = rowpos + 1;
        vertpos = vertpos -2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 4 && board[rowpos + 2][vertpos + 1] == 0){
        rowpos = rowpos + 2;
        vertpos = vertpos +1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 5 && board[rowpos + 2][vertpos - 1] == 0){
        rowpos = rowpos + 2;
        vertpos = vertpos -1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 6 && board[rowpos - 2][vertpos - 1] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos -1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 7 && board[rowpos -2 ][vertpos +1] == 0){
        rowpos = rowpos -2;
        vertpos = vertpos +1;
        board[rowpos][vertpos]=count;
    }
    else{
        System.out.print("You moved " +count +" times.");
        break;
    }

}
}

}
false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

0

It appears you are checking positions even if there are outside the board. For instance, the following line

if (gen == 0 && board[rowpos + 1][vertpos + 2] == 0) ...

will throw an exception if vertpos >= 6 or rowpos == 7, both of which are possible. Likewise,

if (gen == 1 && board[rowpos - 1][vertpos - 2] == 0) ...

throws an exception if rowpos == 0 or if vertpos <= 1.

You need to handle these cases by verifying that a position is within the board before checking if the position has already been visited.

Additionally, you should try to refactor your code so it is less repetitive. If you need more help with that, https://codereview.stackexchange.com/ might be a good place to go, but be sure to work through it as far as you can alone before getting help from others.

Community
  • 1
  • 1
hkk
  • 2,069
  • 1
  • 23
  • 48