Introduction to Backtracking (original) (raw)

Last Updated : 20 Dec, 2025

Backtracking is a problem-solving algorithmic technique that involves finding a solution incrementally by trying **different options and **undoing them if they lead to a **dead end.

frame_3105

How does Backtracking work?

Backtracking is a systematic trial-and-error technique where we build a solution step by step and undo (or “backtrack”) whenever we hit a dead end.

The idea is simple:

Backtracking ensures we don’t waste time pursuing impossible paths. Instead, it systematically explores only feasible ones by backing up whenever a choice fails.

Example - N Queens Problem

In the N-Queens problem, the goal is to place N queens on an N×N chessboard so that no two queens attack each other.

the_knight_s_tour_problem_8

Without backtracking, we would have to test all possible arrangements of queens (which grows exponentially). Most of these arrangements are invalid because queens attack each other. By checking validity at every step (no two queens in the same column or diagonal), backtracking saves time by stopping early whenever a partial placement becomes invalid, ensuring we only explore feasible board states.

Backtracking vs Recursion

Please refer Recursion vs Backtracking for details.

**When to Use Backtracking

**When Not to Use Backtracking

Standard Backtracking Problems

For more practice problems: click here