What is the N-Queens Problem?
The N-Queens Problem asks you to place N chess queens on an N×N board so that no two queens attack each other - meaning no two share a row, column, or diagonal. It is one of the classic examples used to teach backtracking, because the constraints are simple to check but the search space grows factorially.
Backtracking solves it by placing queens one row at a time. Whenever a placement conflicts with an existing queen, the algorithm immediately abandons that branch instead of exploring it further - the same "fail fast, undo, retry" pattern used by the Sudoku Solver and Hamiltonian Path visualizers.
Time & Space Complexity
- Worst Case TimeO(N!)
- Space (Recursion + Board)O(N)
- Conflict CheckO(N)
* Pruning conflicting branches early makes the practical runtime far better than the theoretical worst case.
Why Backtracking?
- ✓Constraint SatisfactionEach row's choice only needs to be checked against rows already placed.
- ✓Early PruningA conflicting placement is rejected immediately, without exploring the rows beneath it.
- ✓Undo on FailureRemoving the last queen and trying the next column is the core "backtrack" step.