Given an integer n, return all distinct solutions to placing n non-attacking queens on an n x n chessboard. Each solution should be represented as an array of n strings, where each string has length n, 'Q' marks a queen, and '.' marks an empty square.
For this question, keep the output deterministic: list boards in the natural depth-first search order created by placing queens row by row, and at each row trying columns from left to right (column 0, then 1, then 2, and so on). When a placement leads to a full valid board, record it immediately; that DFS/backtracking discovery order is the required output order.
Input / output
- Input:
n: int - Output:
string[][]in DFS order
More examples
n = 1returns[["Q"]].n = 2returns[].
Constraints
1 <= n <= 9
Follow-up
How would you count the number of valid boards without constructing every board string, and why is that usually faster?
Examples
Example 1
Example 2
Example 3
Running will execute all 8 cases, including 5 hidden ones.