Backtracking PDF
Backtracking PDF
dead end
?
dead end
dead end
?
start ? ? dead end
dead end
?
success!
12
Terminology I
A tree is composed of nodes
14
• N-Queens problem – permutations with
backtracking
• Hamiltonian circuit problem
• Sub set sum problem
• Soduko – counting with backtracking
• Scheduling – subsets with backtracking
N-Queens problem
Solution :
2 4 13
3142
N queens -Algorithm
1) Start in the leftmost column
2) If all queens are placed
return true
3) Try all rows in the current column.
Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row, column]
as part of the solution and recursively check if placing queen here leads to a
solution.
b) If placing the queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then unmark this [row, column]
(Backtrack) and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked, return false to trigger
backtracking.
• Time Complexity for finding the Hamiltonian Cycle using the Backtracking
approach is O(N!), where N is the number of vertices in the graph.
Hamiltonian Circuit Problem
Hamiltonian Circuit Problem