On an n by n chessboard you must place n queens so that no two of them threaten each other. A queen attacks any piece sharing its row, its column, or either of its two diagonals, so a valid arrangement keeps every pair of queens off the same row, column, and diagonal.
Return all distinct board layouts that satisfy this rule. Represent each board as a list of strings where the character 'Q' marks a queen and '.' marks an empty square.
Example 1
Input: n = 4
Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
There are exactly two ways to place four non-attacking queens on a four by four board.
Example 2
Input: n = 1
Output: [["Q"]]
A single queen on a one by one board trivially satisfies the rule.
Constraints
1 <= n <= 9Exactly one queen is placed in each row and each columnNo two queens may share a diagonalSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI