I'm studying the n-queen backtracker. Can someone explain to me how other_row_pos
checks for diagonals? I'm not sure why it works or how it works.
taken from wikibooks - http://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/N-Queens:
bool isSafe(int queen_number, int row_position) {
// Check each queen before this one
for(int i=0; i<queen_number; i++) {
// Get another queen's row_position
int other_row_pos = position[i];
// Now check if they're in the same row or diagonals
if(other_row_pos == row_position || // Same row
other_row_pos == row_position - (queen_number-i) || // Same diagonal
other_row_pos == row_position + (queen_number-i)) // Same diagonal
return false;
}
return true;
}
# No two queens can be on the same diagonal. # Solve the model. # Statistics. # By default, solve the 8x8 problem. // OR-Tools solution to the N-queens problem. // Instantiate the solver. cp_model. NewIntVar ( range ).
So the diagonal constraint is that the values of queens (i) + i must all be different, and likewise the values of queens (i) - i must all be different, for different i. The code above adds this constraint by applying the AllDifferent method to queens [j] + j and queens [j] - j , for each i.
Data Structures & Algorithms Multiple Choice Questions on “N Queens Problem”. 1. In how many directions do queens attack each other? Clarification: Queens attack each other in three directions- vertical, horizontal and diagonal. 2. Placing n-queens so that no two queens attack each other is called?
However, constraint propagation then forces a queen into the second row of the third column, leaving no valid spots for the fourth queen: And so the solver must backtrack again, this time all the way back to the placement of the first queen. We have now shown that no solution to the queens problem will occupy a corner square.
Let delta_row
= the difference in rows between the two queens, and delta_col
= the difference in columns. The two queens will be on the same diagonal if delta_row == delta_col
or delta_row == -delta_col
.
With the variables you have:
delta_row = other_row_pos - row_position
delta_col = queen_number - i
So the queens are on the same diagonal if:
other_row_pos - row_position == queen_number - i ||
other_row_pos - row_position == -(queen_number - i)
If you add row_position
to both sides of the equality, you get the condition in your code:
other_row_pos == row_position + (queen_number-i) ||
other_row_pos == row_position - (queen_number-i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With