A problem solving technique with a depth-first search algo used to find solution incrementally by trying out different options and undoing them if they lead to a dead end. When a dead end is reached, the algorithm backtracks to the previous decision point and exploresa different path until a solution is found or all the options have been exhausted.
Used for situations where you need to explore multiple possibilities to solve a problem like - searching for a path in a maze, solving a sudoku.
Generally, every constraint satisfaction problem can be solved using backtracking, but Is it optimal to use backtracking every time?
Turns out NO, there are a vast number of problems that can be solved using Greedy or Dynamic programming in logarithmic or polynomial time complexity which is far better than exponential complexity of Backtracking. However many problems still exists that can only be solved using Backtracking.
DP fails here because opening/closing one box does not affect the other box’s outcome. No property of overlapping subproblems.
Greedy approach fails here because it chooses local maxima to get the global maxima. Here, all boxes have equal probability of having the coin. So, no criteria to decide a local maxima at all.
Backtracking works because it is simply brute forcing every route. We choose one box each time and close it back if it doesn’t have the coin which acts as the BACKTRACKING step.
Since it is a plain brute force approach, the time complexity is usually exponential : O ( K^N ) or factorial : O ( N! )
Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of chess knight must visit each square exactly once. Print the order of each cell in which they are visited.