HardBacktrackingRecursionArray

N-Queens

LeetCode
1 approach, code in all languages

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 <= 9
  • Exactly one queen is placed in each row and each column
  • No two queens may share a diagonal
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now