hardBacktrackingMicrosoftAmazon
Royal Court Standoff
A chess tutor arranges N queens on an N×N board so none attack each other across rows, columns, or diagonals.
The n-queens puzzle places n queens on an n×n chessboard such that no two queens attack each other. Return all distinct solutions.
Choose approach
♛
r
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1/18
Narrationstep 1 of 18
Place queen at (0,0).
Variables
row=0
placed=1
solutions=0
How to think about it
- Row-by-row placement eliminates row conflicts implicitly.
- `r - c` identifies ↘ diagonals; `r + c` identifies ↙ diagonals.
- On backtrack, undo set insertions.
Edge cases to catch in interview
- n = 1 -> single trivial solution.
- n = 2 or 3 -> no solution.
Examples
Example 1
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]{"n":4,"grid":[[".",".",".","."],[".",".",".","."],[".",".",".","."],[".",".",".","."]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed