DAA - Backtracking.pptx
DAA - Backtracking.pptx
Algorithms
-Backtracking
What is Backtracking?
Backtracking can be defined as a general algorithmic technique that considers searching
every possible combination in order to solve a computational problem.
Backtracking is finding the solution of a problem whereby the solution depends on the
previous steps taken.
For example,
A maze problem
Assembling Lego pieces
Sudoku
NQueens Problem
Subset Sum Problem
Knapsack Problem
Tower of Hanoi
What is Backtracking?
A backtracking algorithm tries to construct a solution to a computational problem
incrementally, one sub solution at a time.
Whenever the algorithm needs to decide between multiple alternatives to the next component
of the solution, it recursively evaluates every alternative and then chooses the best one.
What is Backtracking?
A backtracking algorithm tries to construct a solution to a computational problem
incrementally, one sub solution at a time.
Whenever the algorithm needs to decide between multiple alternatives to the next component
of the solution, it recursively evaluates every alternative and then chooses the best one.
Steps of Backtracking Algorithm:
The general steps of backtracking are:
● If not, then come back and change the sub-solution and continue again
Why Backtracking?
if x is 0 // base case
return 1
Base Case: Any recursive method must have a terminating condition. Terminating condition
is one for which the answer is already known and we just need to return that. For example for
the factorial problem, we know that factorial(0)=1, so when x is 0 we simply return 1,
otherwise we break into smaller problem i.e. find factorial of x−1
.
Recursion
Backtracking - Algorithmic Design Technique
● At each stage, there will be a number of options, choose one of these option.
● Then will get a new set of options based on the choice selected.
● This procedure is repeated over and over until a final state is reached.
● If a good sequence of choices are made, will reach a final state (a goal state);
if didn't, it isn't.
Backtracking
Example
Backtracking
Example
Objective : To place N Queens in NxN chess board so that no queen is attacked by any other
Constraint : 1<=N<=10
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem
NQueens Problem - Pseudocode
Sample Input : 4
for j in 1 to N 0 0 0 1
if ! IS-ATTACK (row, j, board, N)
board[row][j] = 1 1 0 0 0
T(n) = O(N!)
N- No. of Queens to be placed