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...
Everything is working fine, but I'm trying to get the coordinates of all the possible solutions. The problem is that if I put it inside col == n
it just prints the last one. Any ideas of how to solve this?
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)
{
System.out.println("("+row + "," + col);
System.out.println("solution=" + solution);
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 = scanner.nextInt();// TODO Auto-generated method stub
int queens[] = new int[n+1];
placement(1,queens,n);
System.out.println("nQueens: solution=" + solution);
}
static boolean check_Queen(int row, int col, int queens[])
{
//boolean flag = false;
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(col>=2&&(queens[col-2] == (row -1) || queens[col-2] == (row+1) || queens[col-1] == (row-2) || queens[col-1] == (row+2)))
{
return false;
}
return true;
}
}