AceYourInterviews
Checking sign-in…

125. N-Queens

AdvancedRow-by-row constructive search with column and diagonal ownership

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Safe placements prune attacks and produce both four-queen boards

4
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]