Search code examples
c++n-queens

How do you test for diagonal in n-queens?


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

Solution

  • 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)