What is Backtracking?
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. It is commonly used in situations where you need to explore multiple possibilities to solve a problem, like searching for a path in a maze or solving puzzles like Sudoku. When a dead end is reached, the algorithm backtracks to the previous decision point and explores a different path until a solution is found or all possibilities have been exhausted.
Backtracking can be defined as a general algorithmic technique that considers searching every possible combination in order to solve a computational problem.
Basic Terminologies
- Candidate: A potential choice or element that can be added to the current solution.
- Solution: A valid and complete configuration that satisfies all problem constraints.
- Partial Solution: An intermediate or incomplete configuration being constructed during the backtracking process.
- Decision Space: The set of all possible candidates or choices at each decision point.
- Decision Point: A specific step in the algorithm where a candidate is chosen and added to the partial solution.
- Feasible Solution: A partial or complete solution that adheres to all constraints.
- Dead End: Occurs when a partial solution cannot be extended without violating constraints.
- Backtrack: Involves undoing previous decisions and returning to a prior decision point.
- Search Space: Includes all possible combinations of candidates and choices.
- Optimal Solution: The best possible solution in optimization problems.
Types of Backtracking Problems
Backtracking problems can be categorized into three main types:
- Decision Problems: These involve searching for a feasible solution. For example, determining if there exists a subset of numbers that sum up to a given value.
- Optimization Problems: In these problems, the goal is to find the best solution among all feasible solutions. An example is finding the shortest path in a graph.
- Enumeration Problems: These require finding all possible feasible solutions. For instance, generating all permutations of a given set of numbers.
How Does Backtracking Work?
Backtracking algorithms explore each possible path in order to find a valid solution. This exploration can be understood through the following concepts:
As shown in the image, “IS” represents the Initial State where the recursion call starts to find a valid solution.
- IS (Initial State): The starting point of the recursion.
- C (Checkpoints): Different stages in the recursive calls where decisions are made.
- TN (Terminal Nodes): Points where no further recursive calls can be made. These nodes act as the base cases of the recursion, where the current solution is evaluated.
At each Checkpoint, the program makes decisions and moves to other checkpoints until it reaches a Terminal Node. At the Terminal Node, the program determines if the current solution is valid. If the solution is not valid, the program backtracks to the previous checkpoints and explores other paths. For example, in the diagram, TN1 to TN5 are terminal nodes where the solution is not acceptable, while TN6 is where a valid solution is found.
The back arrows in the image illustrate backtracking in action, where the program reverts changes made at checkpoints and explores alternative paths.
Determining Backtracking Problems
Generally, every constraint satisfaction problem can be solved using backtracking. But is it optimal to use backtracking every time? The answer is no. Many problems can be solved using Greedy or Dynamic Programming approaches in logarithmic or polynomial time complexity, which is far better than the exponential complexity of backtracking. However, many problems still exist that can only be solved using backtracking.
To understand whether a problem is backtracking-based, consider the following example:
Problem Example
Problem: Imagine you have three closed boxes, among which two are empty and one has a gold coin. Your task is to find the gold coin.
Why Dynamic Programming Fails
Does opening or closing one box affect the other boxes? No, each box is independent, and the state of one box cannot determine the transition for the other boxes. Hence, dynamic programming fails because there is no overlapping subproblem or optimal substructure property.
Why Greedy Fails
The Greedy algorithm chooses a local maximum to get a global maximum. In this problem, each box has an equal probability (1/3) of containing the gold coin, so there is no criterion to make a greedy choice.
Why Backtracking Works
Backtracking works by brute-forcing each choice. We can choose each box one by one to find the gold coin. If a box is empty, we can close it back, which acts as a backtracking step.
Backtracking Algorithm
For backtracking problems:
- The algorithm builds a solution by exploring all possible paths created by the choices in the problem, starting with an empty set
S = {}.
- Each choice creates a new subset
s, which we add to our set S.
- Two cases arise:
S + s is a valid set.
S + s is not a valid set.
If the set is valid, we make further choices and repeat the process until a solution is found. Otherwise, we backtrack our decision of including s and explore other paths until a solution is found or all possible paths are exhausted.
Pseudocode for Backtracking
The best way to implement backtracking is through recursion. The backtracking algorithm can be summarized with the following pseudocode:
void FIND_SOLUTIONS(parameters):
if (valid_solution):
store_the_solution
return
for (all_choices):
if (valid_choice):
APPLY(choice)
FIND_SOLUTIONS(parameters)
BACKTRACK(remove_choice)
return
Complexity Analysis of Backtracking
Since the backtracking algorithm is purely brute force, it performs very poorly in terms of time complexity. Generally, backtracking can have the following time complexities:
- Exponential (O(K^N)): This complexity arises when there are multiple choices at each step, leading to a rapid increase in the number of paths and sub-trees.
- Factorial (O(N!)): This complexity occurs in problems where all permutations or combinations are considered, resulting in factorial growth of possible solutions.
These complexities are due to the fact that at each state, we have multiple choices, causing the number of paths to increase and sub-trees to expand rapidly.
How Backtracking is Different from Recursion?
Recursion and backtracking are related concepts in computer science and programming, but they are not the same thing. Let’s explore the key differences between them:
| Recursion |
Backtracking |
| Recursion does not always need backtracking. |
Backtracking always uses recursion to solve problems. |
| Solves problems by breaking them into smaller, similar subproblems and solving them recursively. |
Solves problems with multiple choices, exploring options systematically, and backtracking when needed. |
| Controlled by function calls and call stack. |
Managed explicitly with loops and state. |
| Applications of Recursion: Tree and Graph Traversal, Towers of Hanoi, Divide and Conquer Algorithms, Merge Sort, Quick Sort, and Binary Search. |
Applications of Backtracking: N Queen problem, Rat in a Maze problem, Knight’s Tour Problem, Sudoku solver, and Graph coloring problems. |
Applications of Backtracking
Backtracking is a powerful algorithmic technique that finds application in various fields. Some notable applications include:
- Creating Smart Bots for Board Games: Used in games like Chess to explore possible moves and strategies.
- Solving Mazes and Puzzles: Effective for problems such as the N-Queen problem, Sudoku, and other complex puzzles.
- Network Routing and Congestion Control: Helps in finding optimal paths and managing network traffic efficiently.
- Decryption: Used in cryptographic algorithms to explore possible keys and decrypt messages.
- Text Justification: Used in formatting text to ensure proper alignment and spacing in documents.
Must Do Backtracking Problems
Here are some essential backtracking problems you should try: