N-Queens

Hard#51row by row

Place n chess queens on an n × n board so that no two share a row, a column or a diagonal. Return every such board, drawn with Q for a queen and a dot for an empty cell. Our example: n = 5 has 10 boards.

input
n: the size of an n × n chessboard.
returns
Every way to place n queens on the board so that no two attack each other: no two in one row, one column or one diagonal. A board is n strings, its rows from the top, with 'Q' for a queen and '.' for an empty square. The boards in any order.
constraints
  • 1 ≤ n ≤ 9
our 9 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @return {string[][]}
 */
function solveNQueens(n) {

}
Ctrl ↵
format
reset

saved in this browser

9 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more backtracking problems

Pattern “Backtracking” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.