102. N queens
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
n = 42Example 2
n = 11Example 3
n = 30Constraints
nis a whole number from 1 to 9.
Submit also runs 6 more tests you can't see.
- Place one queen per row with a helper that takes the row number and returns how many ways the remaining rows can be filled. When the row number reaches
n, every queen is placed: that is 1 way. - Keep three sets of what is taken: columns, and the two diagonals. Every square on one diagonal has the same
r - c, and on the other the samer + c. - For each free column, add it to the three sets, count the ways for the next row, then remove it again (backtrack) before trying the next column.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.