What is Backtracking?
- It is a systematic way to iterate through all the possible configurations of a search space.
- It is a general algorithm which must be customized for each application.
- It is really just depth-first search on an implicit graph of configurations.
- Can easily be used to iterate through all subsets or permutations of a set.
- Ensures correctness by enumerating all possibilities.
- For backtracking to be efficient, we must prune dead or redundent branches of the search space whenever possible.
General Algorithm
1 | Backtrack-DFS(A, k): |
Implementation
1 | class Combinatorial_Search: |
is_a_solution(current_answer, kth, info)
This Boolean function tests whether the first k elements of vector current_answer form a complete solution for the given problem.
The last argument, info, allows us to pass general information into the routine.
construct_candidates(current_answer, kth, info)
This routine return an array with the complete set of possible candidates for the kth position of current_answer, given the contents of the first k-1 positions.
process_solution(current_answer, kth, info)
This routine prints, counts, or whatever processes a complete solution once it is constructed.
make_move(current_answer, kth, info) and unmake_move(current_answer, kth, info)
These routines enable us to modify a data structure in response to the latest move, as well as
clean up this data structure if we decide to take back the move.
Applications
- Constructing all subsets
- Constructing all permutations
- Constructing all paths in a graph
- N queens problem
- Rat in a maze problem
References
- The Algorithm Design Manual: Steven S Skiena
- https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1