Generate all safe queen placements on board
TikTokMachine Learning Engineer · Technical ScreenLast updated
This question evaluates algorithm design for constraint-satisfaction problems, testing skills in search, recursion, backtracking, combinatorics, and state-space pruning.
You are given an integer n representing the size of a chessboard (n × n). You need to place n queens on the board so that no two queens attack each other.
A queen can attack another piece if they are on the same row, same column, or same diagonal.
Return all distinct valid configurations of the board.
- Each configuration should be represented as an array (or list) of
nstrings. - Each string has length
nand represents one row of the board. - Character
'Q'represents a queen, and'.'represents an empty square.
Two configurations are considered different if they differ in at least one row string.
You may assume:
1 ≤ n ≤ 9.
Example
Input:
n = 4
One valid output (order of configurations and rows does not matter):
[
[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.",
"Q...",
"...Q",
".Q.."]
]
In each configuration above, there are 4 queens on the board, and no two queens attack each other.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.