Back to coding

Backtracking

Competitive Programming/Backtracking.md

A backtracking algorithm begins with an empty solution and extends the solution step by step. The search recursively goes through all different ways how a solution can be constructed. Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution.

The following is a general outline of how a backtracking algorithm works:

  1. Choose an initial solution.
  2. Explore all possible extensions of the current solution.
  3. If an extension leads to a solution, return that solution.
  4. If an extension does not lead to a solution, backtrack to the previous solution and try a different extension.
  5. Repeat steps 2-4 until all possible solutions have been explored.

Possible ways to place 4 queens on a 4 x 4 chessboard
Figure 1. Possible ways to place 4 queens on a 4 x 4 chessboard.png