125. N-Queens
Place n queens on an n-by-n board so that no two share a row, column, or diagonal. Return every valid board using the specified Q-and-dot representation.
Each complete board must contain exactly n queens. Rotations and reflections are not automatically deduplicated unless the contract explicitly treats them as the same board.
Example 1
Input
n=4
Output
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: The column vectors [1,3,0,2] and [2,0,3,1] are the two distinct arrangements.
Example 2
Input
n=2
Output
[]
Explanation: A separate column forces a diagonal attack.
Example 3
Input
n=0
Output
[[]]
Explanation: One empty arrangement exists; no negative-length diagonal array is allocated.
Constraints
0 <= n <= 10
Hints
Hint 1
Fix one queen per row so only column and diagonal conflicts remain.
Hint 2
Which coordinate expressions stay constant along each diagonal direction?
Hint 3
Claim a free column and both diagonals, recurse to the next row, then restore all three flags and the row position.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Safe placements prune attacks and produce both four-queen boards
4
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]