-1

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);
  }

}
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
user1665569
  • 191
  • 4
  • 8
  • 17

1 Answers1

0

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)))
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • yeah that is happening. My knight search is not right though. i don't think it's moving in a L shape – user1665569 Feb 14 '13 at 23:30
  • THere are four position a knight can move to left of the current position. You have only checked (-2, 1) and (-2, -1), but (-1, 2) and (-1, -2) are also valid. Remember the array safety check will be different based on how far you move left. – Mel Nicholson Feb 14 '13 at 23:51