Backtracking
Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point of time (by time, here, is referred to the time elapsed till reaching any level of the search tree).
Backtracking can be defined as a general algorithmic technique that considers searching every possible combination in order to solve an optimization problem.
However, most of the problems that are discussed, can be solved using other known algorithms like _Dynamic Programming _or _Greedy Algorithms _in logarithmic, linear, linear-logarithmic time complexity in order of input size, and therefore, outshine the backtracking algorithm in every respect (since backtracking algorithms are generally exponential in both time and space). However, a few problems still remain, that only have backtracking algorithms to solve them until now.
Pseudo Code for Backtracking:
1, Recursive backtracking solution.
void findSolutions(n, other params) :
if (found a solution) :
solutionsFound = solutionsFound + 1;
displaySolution();
if (solutionsFound >= solutionTarget) :
System.exit(0);
return
for (val = first to last) :
if (isValid(val, n)) :
applyValue(val, n);
findSolutions(n+1, other params);
removeValue(val, n);
2, Finding whether a solution exists or not
boolean findSolutions(n, other params) :
if (found a solution) :
displaySolution();
return true;
for (val = first to last) :
if (isValid(val, n)) :
applyValue(val, n);
if (findSolutions(n+1, other params))
return true;
removeValue(val, n);
return false;