N-Queens II

Hard#52row by row

Place n chess queens on an n × n board so that no two share a row, a column or a diagonal, and return how many ways there are. Only the number is needed, not the boards. Our example: n = 5 has 10 ways.

input
n: the size of an n × n chessboard.
returns
In how many ways n queens can stand on the board so that no two attack each other: no two in one row, one column or one diagonal.
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 {number}
 */
function totalNQueens(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.