If col
is 0 or 1, then you will get an ArrayIndexOutOfBoundsException
. Add a check before accessing the array.
if ((col >= 2) && (queens[col-2] == (row-1) || queens[col-2] == (row+1)))
Question
I'm trying to implement the N*N
queen algorithm with a little twist to it. In this version the queen can also move like a Knight can in chess.
Checking for the diagonals and rows seems to be fine, however when I try to check for a queen in the "L" position away from my current position, I get a "arrayindexoutofboundexception". I'm not entirely sure if my check_Knight move is right. I can't seem to locate the error causing the issue in my code.
public class QueenGame {
/**
* @param args
*/
static int solution =0;
static boolean check_Queen(int row, int col, int queens[])
{
for(int i =1; i<col; i++)
{
if (queens[col-i] == row ||
queens[col-i] == row-i ||
queens[col-i] == row+i)
{
//flag = false;
return false;
}
}
return true;
}
static boolean check_KnightMove(int row, int col, int queens[])
{
if(queens[col-2] == (row -1) || queens[col-2] == (row+1))
{
return false;
}
return true;
}
static void placement(int col, int queens[], int n){
//int solution =0;
for (int row = 1; row <= n; row++) {
queens[col] = row;
if((check_Queen(row,col,queens)) == true)
{
if((check_KnightMove(row,col,queens)) == true)
{
if(col == n)
{
solution++;
}
else
{
placement(col+1,queens,n);
}
}
}
}
queens[col] = 0;
}
public static void main(String[] args) {
int solution =0;
Scanner scanner=new Scanner(System.in);
//System.out.print("Please enter N");
int n =10;
//int n = scanner.nextInt();// TODO Auto-generated method stub
//System.out.print(n);
int queens[] = new int[n+1];
placement(1,queens,n);
System.out.println("nQueens: solution=" + solution);
}
}
Solution
If col
is 0 or 1, then you will get an ArrayIndexOutOfBoundsException
. Add a check before accessing the array.
if ((col >= 2) && (queens[col-2] == (row-1) || queens[col-2] == (row+1)))