N-Queens
hardLeetCode Top 100backtracking
Problem
Given a number n, place n queens on an n by n chessboard so that no two attack each other, and return all distinct board configurations. Queens attack along rows, columns, and both diagonals.
Examples
Input: n = 4
Output: 2 distinct solutions
There are two ways to place four non-attacking queens.
Input: n = 1
Output: 1 solution
A single queen on a single cell.
Constraints
- • 1 <= n <= 9
Hints(tap to reveal)
- 1. Place one queen per row.
- 2. Track occupied columns and diagonals for O(1) conflict checks.
Optimal approach(spoiler)
- Place queens row by row, choosing a safe column in each.
- Track used columns, and both diagonal directions in sets.
- Skip columns whose column or diagonal sets conflict.
- Record a full board when all rows are placed, then backtrack.
- Pruning keeps the search far below the naive bound.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor