Skip to content
BASA DSA

N Queens

HardBacktracking

Place n queens on an n by n board so that no two share a row, column or diagonal. Return every board as an array of row strings, with Q for a queen and dots elsewhere. Result order is unrestricted.

Example 1

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

Explanation

The two n=4 boards each use distinct columns and diagonals with one queen per row.

Example 2

Input
n = 2
Output
[]

Explanation

Two queens on a 2-by-2 board always share a row, column or diagonal.

Example 3

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

Explanation

One queen fits the only cell.

Constraints

  • 1 <= n <= 9

Function contractsolveNQueensArguments: json
Loading draft…
SolutionRuns on your device
Loading draft…