CodeArchon

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).

1def solveNQueens(n):
2 out, cols, d1, d2 = [], set(), set(), set()
3 board = [['.']*n for _ in range(n)]
4 def dfs(r):
5 if r == n:
6 out.append([''.join(row) for row in board]); return
7 for c in range(n):
8 if c in cols or (r-c) in d1 or (r+c) in d2: continue
9 board[r][c] = 'Q'; cols.add(c); d1.add(r-c); d2.add(r+c)
10 dfs(r+1)
11 board[r][c] = '.'; cols.discard(c); d1.discard(r-c); d2.discard(r+c)
12 dfs(0); return out
Variables
row=0
placed=1
solutions=0

How to think about it

  1. Row-by-row placement eliminates row conflicts implicitly.
  2. `r - c` identifies ↘ diagonals; `r + c` identifies ↙ diagonals.
  3. 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