/51. N-Queens

51. N-Queens

Hard
Arrays75.1% acceptance

Given an integer board_size, return all distinct arrangements of placing board_size queens on a board_size x board_size grid such that no two queens threaten each other. Each arrangement should be represented as a list of strings, where Q denotes a queen and . denotes an empty cell. The order of solutions does not matter.

Example 1

Input: 2

Output: []

Explanation: No valid arrangement exists for board_size = 2.

Example 2

Input: 3

Output: []

Explanation: No valid arrangement exists for board_size = 3.

Example 3

Input: 5

Output: [[Q....,.Q...,...Q.,..Q..,....Q],[Q....,..Q..,....Q,.Q...,...Q.],[.Q...,...Q.,Q....,..Q..,....Q],[.Q...,....Q,..Q..,Q....,...Q.],[..Q..,Q....,...Q.,.Q...,....Q],[..Q..,....Q,.Q...,Q....,...Q.],[...Q.,Q....,..Q..,....Q,.Q...],[...Q.,.Q...,....Q,..Q..,Q....],[....Q,.Q...,...Q.,Q....,..Q..],[....Q,..Q..,Q....,...Q.,.Q...]]

Explanation: There are 10 valid arrangements for board_size = 5.

Constraints

  • 1 <= board_size <= 9
Python (current runtime)

Case 1

Input: 4

Expected: [['.Q..','...Q','Q...','..Q.'],['..Q.','Q...','...Q','.Q..']]

Case 2

Input: 1

Expected: [['Q']]

Case 3

Input: 6

Expected: [['Q.....','..Q...','....Q.','.Q....','.....Q','...Q..'],['Q.....','...Q..','.Q....','.....Q','..Q...','....Q.'],['.Q....','...Q..','Q.....','.....Q','..Q...','....Q.'],['.Q....','....Q.','..Q...','Q.....','...Q..','.....Q'],['..Q...','Q.....','....Q.','.Q....','...Q..','.....Q'],['..Q...','.....Q','.Q....','Q.....','...Q..','....Q.'],['...Q..','Q.....','..Q...','....Q.','.....Q','.Q....'],['...Q..','.Q....','.....Q','..Q...','Q.....','....Q.'],['....Q.','.Q....','...Q..','Q.....','..Q...','.....Q'],['....Q.','..Q...','Q.....','...Q..','.Q....','.....Q']]