Backtracking (N-Queens)
Software Engineer path · lesson 40 of 99Solve complex problems by building candidates step-by-step and abandoning them ("backtracking") as soon as they fail constraints.
n = 3 has no solution: watch the search prove it.
Place 5 queens on a 5×5 board, one per row, so none attack each other.
- 1place(row):
- 2 if row == n: record a solution
- 3 for col in 0..n-1:
- 4 if no queen shares col or a diagonal with (row, col):
- 5 put a queen at (row, col); place(row + 1)
- 6 remove it # backtrack
- Placements tried
- 0 / 15
- Backtracks
- 0 / 0
Solutions found: 0
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
N-Queens
Order the steps of the backtracking search.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
What distinguishes Backtracking from Brute Force?
Write the code
Permutations
function permute(nums) {
// Your code here
}The short version
Think of trying to solve a Sudoku puzzle. You fill in a number. If it works, you move to the next square. If you get stuck later, you erase your last move and try a different number.
In more depth
Try and Undo
Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally.
The Strategy:
Pruning:
Crucially, if a partial solution cannot possibly be completed to a valid solution, we abandon it immediately (prune the tree), saving huge amounts of time compared to pure Brute Force.
When to reach for this
- Find **ALL** solutions (Permutations, Combinations, Subsets)
- Solving puzzles (Sudoku, N-Queens)
- Constraint satisfaction problems
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required