Backtracking

This introductory guide to Backtracking, you will explore the foundational principles of DSA, understand their significance and applications, discover effective strategies for learning, and step-by-step journey for beginners.

Overveiw

Chapters

9 Chapters are there for this module. We will cover all concepts related to Backtracking.

Start learning

../Practice/All-DSA-Problems.html

Quiz on the topics being learnt in this module to enusure your knowlege.

Quiz

Problems

Practice Problems on the topics being covered in this module.

Practice

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




Types of Backtracking Problems

Backtracking problems can be categorized into three main types:




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:

Backtracking Diagram

As shown in the image, “IS” represents the Initial State where the recursion call starts to find a valid solution.

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:

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:

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:




Must Do Backtracking Problems

Here are some essential backtracking problems you should try: