N-Queens

HardBacktracking

A chess queen attacks every square in its row, its column and both of its diagonals. The n-queens puzzle asks you to place n queens on an n × n board so that no two queens attack each other.

Given n, return every distinct solution. Describe each solution as a board: an array of n strings, one per row from top to bottom, where "Q" marks a queen and "." an empty square. For example, ".Q.." is a row of a 4 × 4 board with a queen in column 1.

Return the boards in any order. If there is no solution, return an empty array.

Constraints

  • 1 <= n <= 9

Examples

Example 1

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

There are exactly two ways to place 4 queens. In the first, the queens sit in columns 1, 3, 0, 2 of rows 0 to 3; the second is its mirror image. The boards may be returned in any order.

Example 2

Input: n = 1
Output: [["Q"]]

One queen on a 1 × 1 board: a single solution.

Example 3

Input: n = 2
Output: []

Two queens on a 2 × 2 board always attack each other (same row, column or diagonal), so there are no solutions.

JavaScript you'll use: Recursion, the call stack and memoization Map and Set Strings and characters

/**
 * @param {number} n
 * @return {string[][]}
 */
function solveNQueens(n) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.