Right now I am trying to solve the problem where there are eight queens on a 8x8 board, and you have to place them where none of them can capture the other. This is pretty popular problem to use recursion on, however I still can't figure out exactly why it is not working. Here is the main code for checking if a placement is valid, and then if it is a valid placement the queen will be placed, otherwise try to place the queen at a position one unit to the right (a new column, same row). Here is the code:
private boolean placeQueen(int row, int column)
{
if(check(row, column))
{
board[column][row] = 'Q';
queenCount++;
return true;
}else if(column == board.length)
{
queenCount++;
return false;
}else
{
return (placeQueen(row, column + 1));
}
//return false;
}
private boolean check(int row, int column)
{
//checking vertical axis
for(int i = 0; i < board.length; i++)
{
if(board[column][i] == 'Q' && i != row)
{ //does not check its own row
return false;
}
}
int i = column;
int j = row;
//left one, up one
while(i >= 0 && j >= 0)
{
try{
if(board[i--][j--] == 'Q')
{
return false;
}else
{
i--;
j--;
}
}catch(ArrayIndexOutOfBoundsException e)
{
break;
}
}
i = column;
j = row;
//right one, up one
while(i <= 8 && j >= 0)
{
try{
if(board[i++][j--] == 'Q')
{
return false;
}else
{
i++;
j--;
}
}catch(ArrayIndexOutOfBoundsException e)
{
break;
}
}
return true;
}
I have to only check for the upward diagonals, since I am placing the queens as it goes down. Here is the output, which is not correct:
Q * * * * * * *
* Q * * * * * *
* * * Q * * * *
* * Q * * * * *
* * * * * * * Q
* * * * * * Q *
* * * * Q * * *
* * * * * Q * *
Is it something with how I am doing it recursively, or just how I am checking the diagonals?
Here is how I am running it
public void run()
{
createBoard();
while(queenCount != board.length)
{
placeQueen(queenCount, 0);
}
printBoard();
}