Backtracking Algorithms
Backtracking Algorithms
Algorithms
Backtracking Algorithms
A backtracking algorithm is a problem-solving algorithm that uses
a brute force approach to find the desired output.
The Brute force approach tries out all the possible solutions and choose
the desired/best solutions. So, its complexity will be very high. While, in
backtracking, only a few solutions are explored.
Approach
Backtrack(x)
if x is not a solution
return false
if x is a new solution
add to list of solutions
backtrack(expand x)
B1 B2 G
B1 B2 G
B2 G B1 G B1 B2
B1B2 B1G B2B1 B2G GB1 GB2
G B2 G B1 B2 B1
Time Complexity
Total possibility for n
B1 G
boys and girls = n!
B2
Time taken to find the
solution that satisfy the
B2 G B1 B2
constraint= n*n!
B1 G
Total time= O(n*n!)
B1B2 B1G B2B1 B2G GB1 GB2
G B2 G B1 B2 B1
Backtrack Backtrack
Positions
(0,0)
0th level Q
1st
2nd
0 1 2 3
0 Q0
3rd
1
2nd
0 1 2 3
0 Q0
3rd
1 Q1
2
F
2nd
Dead end 0 1 2 3
X 0 Q0
3rd
1 Q1
2
F
2nd
Dead end 0 1 2 3
X 0 Q0
3rd
1 Q1
2
Positions
0th level Q0
(0,0)
(1,3)
(2,1)
1st Q1
F
2nd Q2
Dead end 0 1 2 3
X 0 Q0
3rd
1 Q1
2 Q2
3
F
2nd Q2
Dead end 0 1 2 3
X 0 Q0
3rd
Dead end 1 Q1
X
2 Q2
3
F
2nd Q2
Dead end 0 1 2 3
F
X 0 Q0
3rd
Dead end 1 Q1
X
2 Q2
3
Positions
0th level Q0 (0,1)
F (1,3)
(2,3)
1st Q1
F
F
2nd Q2
Dead end 0 1 2 3
F
X 0 Q0
3rd
Dead end 1
X
2
The following is the binary representation of the path shown in the above
diagram.
1.{1, 0, 0, 0}
2.{1, 1, 0, 0}
3.{0, 1, 0, 0}
4.{0, 1, 1, 1}
Only the entries marked using the number 1 represent the path.
DAA (CS-204) PDPM IIITDM, Jabalpur 31
Rat in a Maze problem
Backtrack
Backtrack
Reached to
destination
Space Complexity – O(n2), since to keep the input and solution, 2-D array is
used.