int placement[] = new int[8];
int placeQueen(int row)
{
if(row == 8)
{
printBoard();
return;
}
for(int i = 0; i<8; i++)
{
placement[row] = i;
if(check(row))
{
placeQueen(row + 1); \\This step
}
}
}
boolean check(int row)
{
for(int i = 0; i<row; i++)
{
int diff = Math.abs(placement[row] - placement[i]);
if(diff == 0 || (diff == row - i))
{
return false;
}
}
return true;
}
What I exactly don’t get is how the recursion works inside the for loop.
This algorithm recurses over the rows. It tries adding one queen on row
rat each of eight positions it could be at in the row. Trying this is sufficient because if two queens were placed on the same row you’d violate the condition that no two queens could attack each other.Since one queen is placed at a time, it is sufficient for the
checkfunction to only check that the newly placed queen is not able to attack any of the previously placed queens.diff == 0makes sure the new queen isn’t in the same position as any of the previous queens.diff == row - iensures the new queen can’t attack another along either diagonal movements. (This catches both diagonal movements because of the Math.abs() in the preceding line.)So, again:
Try placing one queen at a time, see if it can’t attack any of the others. If it can, return immediately — otherwise try adding a queen in the next row in all ways possible.