Loading...
Loading...
Place n queens on an n by n chessboard so that no two share a row, a column or a diagonal. Print the number of different placements. If there is at least one, also print the first one found when rows are filled from top to bottom and columns are tried from left to right, as n lines using Q for a queen and . for an empty square.
Example
Input
4
Output
2 .Q.. ...Q Q... ..Q.
Two placements; the first has its queens in columns 1, 3, 0, 2.
Try the problem first. Open one hint at a time.
Put one queen in each row. For each square keep three marks: its column, row - column and row + column.
A square is safe if none of its three marks is taken yet. Add the marks when you place a queen and remove them when you undo it.
Write your Python code, run it on the examples and submit it to hidden tests.
Solve in the editor