150 XP

102. N queens

Expert backtracking

A chess queen attacks every square in its row, its column and both of its diagonals, as far as the board goes. The puzzle is to place n queens on an n by n board so that no queen attacks another.

Write a function count_queens(n) that returns how many different ways there are to do it.

  • Two placements are different if any square differs, even when one is the other turned round or mirrored: the 4 by 4 board has 2 placements, mirror images of each other.
  • A 1 by 1 board has 1 placement; 2 by 2 and 3 by 3 boards have none.

There is exactly one queen in each row, so place them a row at a time: try each column that no queen attacks yet, carry on with the next row, and step back to try the next column when a row has no free square.

Example 1

Inputn = 4
Output2
ExplanationColumns 1, 3, 0, 2 by row, and its mirror.

Example 2

Inputn = 1
Output1
ExplanationOne queen on one square.

Example 3

Inputn = 3
Output0
ExplanationAny two queens on 3 by 3 end up attacking.

Constraints

  • n is a whole number from 1 to 9.

Submit also runs 6 more tests you can't see.

Code
def count_queens(n):
    """Count the ways to place n non-attacking queens.

    n: int, the size of the board and number of queens
    Returns: int, how many placements have no two queens
        attacking each other
    """
    # Write your code here
    pass