DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

What is BackTracking?

Backtracking is a general algorithmic technique that explores all possible solutions to a computational problem by constructing a partial solution incrementally and abandoning it whenever it determines that the partial solution cannot be completed to a valid solution.

Here are the main components and steps involved in backtracking:

Components:

  1. Decision Space: A set of all possible candidates for the next extension of the current partial solution.
  2. Constraints: Rules that the solution must adhere to.
  3. Goal: A condition that determines if the partial solution is a valid solution to the problem.

Steps:

  1. Choose: Pick the next candidate from the decision space.
  2. Constraint Check: Verify if the chosen candidate satisfies all constraints.
    • If it does, proceed to the next step.
    • If it doesn't, backtrack (undo the choice and try another candidate).
  3. Goal Check: Check if the current partial solution satisfies the goal condition.
    • If it does, store or use this solution.
    • If it doesn't, backtrack and try another candidate.

Examples:

N-Queens Problem:

In the N-Queens problem, the decision space is the set of all possible positions where a queen can be placed on the chessboard. The constraints are that no two queens can attack each other (i.e., they can't be in the same row, column, or diagonal). The goal is to place N queens on the N x N chessboard without attacking each other.

Sudoku Solver:

In Sudoku solving, the decision space is the set of all possible numbers (1-9) that can be placed in an empty cell. The constraints are that no row, column, or 3x3 subgrid can contain duplicate numbers. The goal is to fill all empty cells with numbers from 1 to 9 such that the completed Sudoku grid is valid.

Pseudocode for Backtracking:

function backtrack(candidate):
    if candidate is a valid solution:
        store candidate
        return

    for next_candidate in candidates:
        if next_candidate is valid:
            apply next_candidate to candidate
            backtrack(next_candidate)
            remove next_candidate from candidate
Enter fullscreen mode Exit fullscreen mode

Backtracking is widely used in various problems like permutation generation, combination finding, subset generation, and more. It's a powerful technique but can be computationally expensive if not implemented carefully, especially when the decision space is large.

Disclaimer: This article was created with the help of AI.

Top comments (0)