N-Queens
HardBacktracking
Place n queens on an n x n chessboard so that no two queens attack each other. A queen attacks every square in its row, its column, and both of its diagonals, so every row, column and diagonal may hold at most one queen.
Return all distinct solutions. Write each solution as a list of n strings, one per row from top to bottom, where "Q" marks a queen and "." an empty square (row r's string has its "Q" at the queen's column). The solutions may be returned in any order, but the rows inside each board must stay in top-to-bottom order. If there is no solution, return an empty list.
Example 1
- Input:
- n = 6
- Output:
- [[".Q....","...Q..",".....Q","Q.....","..Q...","....Q."],["..Q...",".....Q",".Q....","....Q.","Q.....","...Q.."],["...Q..","Q.....","....Q.",".Q....",".....Q","..Q..."],["....Q.","..Q...","Q.....",".....Q","...Q..",".Q...."]]
- Explanation
- There are exactly four ways to place 6 queens. In the first board the queens sit in columns 1, 3, 5, 0, 2, 4 of rows 0 to 5: no two share a column, and no two are on the same diagonal. The other three boards are its mirror images and rotations.
Example 2
- Input:
- n = 3
- Output:
- []
- Explanation
- Wherever the first two queens go on a 3 x 3 board, every square left for the third queen is attacked, so there is no solution.
Constraints
1 <= n <= 9