#51

N-Queens

Hard Backtracking row by row

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Place n queens on an n×n board so that no two attack each other (same row, column or diagonal). Return all such boards.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: place n queens so none attack each other; list all boards.

Why this works: one queen per row; track used columns and both diagonals (r - c and r + c) so each check is O(1).

Example: n = 4

row 0 col 1, row 1 col 3, row 2 col 0, row 3 col 2 ✓and its mirror: cols 2, 0, 3, 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Checking attacks by scanning the whole board each time — O(n) per check. The three boolean arrays make it O(1).

Solve on LeetCode ↗
Complexity
  • Time: O(n!).
  • Space: O(n).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon