SlideShare a Scribd company logo
1 of 25
PSUCS 311 – Design and Algorithms Analysis Dr. Mohamed Tounsi
Backtracking
PS
2
General Concepts
Algorithm strategy
Approach to solving a problem
May combine several approaches
Algorithm structure
Iterative ⇒ execute action in loop
Recursive ⇒ reapply action to subproblem(s)
Problem type
Satisfying ⇒ find any satisfactory solution
Optimization ⇒ find best solutions (vs. cost metric)
PS
3
A short list of categories
Many Algorithm types are to be considered:
Simple recursive algorithms
Backtracking algorithms
Divide and conquer algorithms
Dynamic programming algorithms
Greedy algorithms
Branch and bound algorithms
Brute force algorithms
Randomized algorithms
PS
4
Backtracking
Suppose you have to make a series of
decisions, among various choices, where
You don’t have enough information to know what to
choose
Each decision leads to a new set of choices
Some sequence of choices (possibly more than one)
may be a solution to your problem
Backtracking is a methodical way of trying out
various sequences of decisions, until you find
one that “works”
PS
5
Backtracking Algorithm
Based on depth-first recursive search
Approach
1. Tests whether solution has been found
2. If found solution, return it
3. Else for each choice that can be made
a) Make that choice
b) Recur
c) If recursion returns a solution, return it
4. If no choices remain, return failure
Some times called “search tree”
PS
6
Backtracking Algorithm – Example
Find path through maze
Start at beginning of maze
If at exit, return true
Else for each step from current location
– Recursively find path
– Return with first successful step
– Return false if all steps fail
PS
7
Backtracking Algorithm – Example
Color a map with no more than four colors
If all countries have been colored return success
Else for each color c of four colors and country n
– If country n is not adjacent to a country that has been
colored c
Color country n with color c
Recursively color country n+1
If successful, return success
Return failure
PS
8
Backtracking
Start
Success!
Success!
Failure
Problem space consists of states (nodes) and actions
(paths that lead to new states). When in a node can
can only see paths to connected nodes
If a node only leads to failure go back to its "parent"
node. Try other alternatives. If these all lead to failure
then more backtracking may be necessary.
PS
9
Recursive Backtracking
Pseudo code for recursive backtracking algorithms
If at a solution, return success
for( every possible choice from current state /
node)
Make that choice and take one step along path
Use recursion to solve the problem for the new node / state
If the recursive call succeeds, report the success to the next
high level
Back out of the current choice to restore the state at the
beginning of the loop.
Report failure
PS
10
Backtracking
Construct the state space tree:
Root represents an initial state
Nodes reflect specific choices made for a solution’s
components.
– Promising and nonpromising nodes
– leaves
Explore the state space tree using depth-first search
“Prune” non-promising nodes
dfs stops exploring subtree rooted at nodes leading to no
solutions and...
“backtracks” to its parent node
PS
11
Example: The n-Queen problem
Place n queens on an n by n chess board
so that no two of them are on the same
row, column, or diagonal
PS
12
State Space Tree of the Four-queens Problem
PS
13
The backtracking algorithm
Backtracking is really quite simple--we “explore”
each node, as follows:
To “explore” node N:
1. If N is a goal node, return “success”
2. If N is a leaf node, return “failure”
3. For each child C of N,
3.1. Explore C
3.1.1. If C was successful, return “success”
4. Return “failure”
PS
14
Exercises
Continue the backtracking search for a solution
to the four-queens problem to find the second
solution to the problem.
A trick to use: the board is symmetric, obtain
another solution by reflections.
Get a solution to the 5-queens problem found by
the back-tracking algorithm?
Can you (quickly) find at least 3 other solutions?
PS
15
The m-Coloring Problem and Hamiltonian Problem
2-color
3-color
Hamiltonian Circuit
(use alphabet order to
break the ties)
c d
a
eb
PS
16
Coloring a map
You wish to color a map with
not more than four colors
red, yellow, green, blue
Adjacent countries must be in
different colors
You don’t have enough information to choose colors
Each choice leads to another set of choices
One or more sequences of choices may (or may not) lead
to a solution
Many coloring problems can be solved with backtracking
PS
17
Comments
Backtracking provides the hope to solve some problem
instances of nontrivial sizes by pruning non-promising
branches of the state-space tree.
The success of backtracking varies from problem to problem
and from instance to instance.
Backtracking possibly generates all possible candidates in an
exponentially growing state-space tree.
PS
18
Other Backtracking Problems *
8 Queens
Knight's Tour
Knapsack problem / Exhaustive Search
Filling a knapsack. Given a choice of items with various
weights and a limited carrying capacity find the optimal
load out. 50 lb. knapsack. items are 1 40 lb, 1 32 lb. 2
22 lbs, 1 15 lb, 1 5 lb. A greedy algorithm would
choose the 40 lb item first. Then the 5 lb. Load out =
45lb. Exhaustive search 22 + 22 + 5 = 49.
PSUCS 311 – Design and Algorithms Analysis Dr. Mohamed Tounsi
Branch and Bound
PS
20
Branch and Bound ( B& B)
An enhancement of backtracking
Similarity
–A state space tree is used to solve a problem.
Difference
–The branch-and-bound algorithm does not
limit us to any particular way of traversing
the tree.
–Used only for optimization problems (since
the backtracking algorithm requires the using
of DFS traversal and is used for non-
optimization problems.
PS
21
Branch and Bound
The idea:
Set up a bounding function, which is used to compute a
bound (for the value of the objective function) at a node
on a state-space tree and determine if it is promising
Promising (if the bound is better than the value of the
best solution so far): expand beyond the node.
Nonpromising (if the bound is no better than the value
of the best solution so far): not expand beyond the node
(pruning the state-space tree).
PS
22
Traveling Salesman Problem
Construct the state-space tree:
A node = a vertex: a vertex in the graph.
A node that is not a leaf represents all the tours that start
with the path stored at that node; each leaf represents a tour
(or non-promising node).
Branch-and-bound: we need to determine a lower bound for
each node
– For example, to determine a lower bound for node [1, 2]
means to determine a lower bound on the length of any
tour that starts with edge 1—2.
Expand each promising node, and stop when all the
promising nodes have been expanded. During this procedure,
prune all the nonpromising nodes.
– Promising node: the node’s lower bound is less than
current minimum tour length.
– Non-promising node: the node’s lower bound is NO less
than current minimum tour length.
PS
23
Traveling Salesman Problem—Bounding Function 1
Because a tour must leave every vertex exactly once, a
lower bound on the length of a tour is b (lower
bound) minimum cost of leaving every vertex.
The lower bound on the cost of leaving vertex v1 is
given by the minimum of all the nonzero entries in
row 1 of the adjacency matrix.
…
The lower bound on the cost of leaving vertex vn is
given by the minimum of all the nonzero entries in
row n of the adjacency matrix.
Note: This is not to say that there is a tour with this
length. Rather, it says that there can be no shorter tour.
Assume that the tour starts with v1.
PS
24
Traveling Salesman Problem—Bounding Function 2
Because every vertex must be entered and exited exactly once,
a lower bound on the length of a tour is the sum of the
minimum cost of entering and leaving every vertex.
For a given edge (u, v), think of half of its weight as the
exiting cost of u, and half of its weight as the entering cost of
v.
The total length of a tour = the total cost of visiting( entering
and exiting) every vertex exactly once.
The lower bound of the length of a tour = the lower bound of
the total cost of visiting (entering and exiting ) every vertex
exactly once.
– Calculation:
for each vertex, pick top two shortest adjacent edges
(their sum divided by 2 is the lower bound of the total
cost of entering and exiting the vertex);
add up these summations for all the vertices.
Assume that the tour starts with vertex a and that b is visited
before c.
PS
25
Traveling salesman example 2

More Related Content

What's hot

Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
chidabdu
 

What's hot (20)

sum of subset problem using Backtracking
sum of subset problem using Backtrackingsum of subset problem using Backtracking
sum of subset problem using Backtracking
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Hill climbing algorithm
Hill climbing algorithmHill climbing algorithm
Hill climbing algorithm
 
N queen problem
N queen problemN queen problem
N queen problem
 
0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Hill climbing
Hill climbingHill climbing
Hill climbing
 
Greedy Algorithm
Greedy AlgorithmGreedy Algorithm
Greedy Algorithm
 
Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking 
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
 
N Queens problem
N Queens problemN Queens problem
N Queens problem
 
Elements of dynamic programming
Elements of dynamic programmingElements of dynamic programming
Elements of dynamic programming
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
 

Viewers also liked

01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
mandlapure
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
Tech_MX
 
lecture 27
lecture 27lecture 27
lecture 27
sajinsc
 
Graph coloring and_applications
Graph coloring and_applicationsGraph coloring and_applications
Graph coloring and_applications
mohammad alkhalil
 

Viewers also liked (20)

backtracking algorithms of ada
backtracking algorithms of adabacktracking algorithms of ada
backtracking algorithms of ada
 
21 backtracking
21 backtracking21 backtracking
21 backtracking
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Backtracking
BacktrackingBacktracking
Backtracking
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Analysis of Feature Selection Algorithms (Branch & Bound and Beam search)
Analysis of Feature Selection Algorithms (Branch & Bound and Beam search)Analysis of Feature Selection Algorithms (Branch & Bound and Beam search)
Analysis of Feature Selection Algorithms (Branch & Bound and Beam search)
 
Backtracking
BacktrackingBacktracking
Backtracking
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
lecture 27
lecture 27lecture 27
lecture 27
 
Branch and Bound Feature Selection for Hyperspectral Image Classification
Branch and Bound Feature Selection for Hyperspectral Image Classification Branch and Bound Feature Selection for Hyperspectral Image Classification
Branch and Bound Feature Selection for Hyperspectral Image Classification
 
Maze Problem Presentation
Maze Problem PresentationMaze Problem Presentation
Maze Problem Presentation
 
Hamiltonian path
Hamiltonian pathHamiltonian path
Hamiltonian path
 
Randomized Algorithms in Linear Algebra & the Column Subset Selection Problem
Randomized Algorithms in Linear Algebra & the Column Subset Selection ProblemRandomized Algorithms in Linear Algebra & the Column Subset Selection Problem
Randomized Algorithms in Linear Algebra & the Column Subset Selection Problem
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Chap08alg
Chap08algChap08alg
Chap08alg
 
Solving The Shortest Path Tour Problem
Solving The Shortest Path Tour ProblemSolving The Shortest Path Tour Problem
Solving The Shortest Path Tour Problem
 
DP
DPDP
DP
 
Branch & bound
Branch & boundBranch & bound
Branch & bound
 
Graph coloring and_applications
Graph coloring and_applicationsGraph coloring and_applications
Graph coloring and_applications
 

Similar to Backtracking

Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
chidabdu
 
ETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptxETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptx
RahulSingh190790
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
chidabdu
 

Similar to Backtracking (20)

Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
 
5.5 back tracking
5.5 back tracking5.5 back tracking
5.5 back tracking
 
Searching techniques
Searching techniquesSearching techniques
Searching techniques
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
 
35 algorithm-types
35 algorithm-types35 algorithm-types
35 algorithm-types
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.ppt
 
ETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptxETCS262A-Analysis of design Algorithm.pptx
ETCS262A-Analysis of design Algorithm.pptx
 
Undecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation AlgorithmsUndecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation Algorithms
 
DAA-Module-5.pptx
DAA-Module-5.pptxDAA-Module-5.pptx
DAA-Module-5.pptx
 
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWERUndecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
state-spaces29Sep06.ppt
state-spaces29Sep06.pptstate-spaces29Sep06.ppt
state-spaces29Sep06.ppt
 
Analysis and design of algorithms part 4
Analysis and design of algorithms part 4Analysis and design of algorithms part 4
Analysis and design of algorithms part 4
 
Stochastic Process Exam Help
Stochastic Process Exam HelpStochastic Process Exam Help
Stochastic Process Exam Help
 
designanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptxdesignanalysisalgorithm_unit-v-part2.pptx
designanalysisalgorithm_unit-v-part2.pptx
 
Nelder Mead Search Algorithm
Nelder Mead Search AlgorithmNelder Mead Search Algorithm
Nelder Mead Search Algorithm
 
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.pptfdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
fdocuments.in_branch-and-bound-design-and-analysis-of-alogorithm.ppt
 
Ai popular search algorithms
Ai   popular search algorithmsAi   popular search algorithms
Ai popular search algorithms
 
Stochastic Process Assignment Help
Stochastic Process Assignment HelpStochastic Process Assignment Help
Stochastic Process Assignment Help
 

More from Vikas Sharma

More from Vikas Sharma (8)

Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Coloring graphs
Coloring graphsColoring graphs
Coloring graphs
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Rules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaRules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharma
 
Office automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaOffice automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharma
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharma
 
Website optimization by vikas sharma
Website optimization by vikas sharmaWebsite optimization by vikas sharma
Website optimization by vikas sharma
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Backtracking

  • 1. PSUCS 311 – Design and Algorithms Analysis Dr. Mohamed Tounsi Backtracking
  • 2. PS 2 General Concepts Algorithm strategy Approach to solving a problem May combine several approaches Algorithm structure Iterative ⇒ execute action in loop Recursive ⇒ reapply action to subproblem(s) Problem type Satisfying ⇒ find any satisfactory solution Optimization ⇒ find best solutions (vs. cost metric)
  • 3. PS 3 A short list of categories Many Algorithm types are to be considered: Simple recursive algorithms Backtracking algorithms Divide and conquer algorithms Dynamic programming algorithms Greedy algorithms Branch and bound algorithms Brute force algorithms Randomized algorithms
  • 4. PS 4 Backtracking Suppose you have to make a series of decisions, among various choices, where You don’t have enough information to know what to choose Each decision leads to a new set of choices Some sequence of choices (possibly more than one) may be a solution to your problem Backtracking is a methodical way of trying out various sequences of decisions, until you find one that “works”
  • 5. PS 5 Backtracking Algorithm Based on depth-first recursive search Approach 1. Tests whether solution has been found 2. If found solution, return it 3. Else for each choice that can be made a) Make that choice b) Recur c) If recursion returns a solution, return it 4. If no choices remain, return failure Some times called “search tree”
  • 6. PS 6 Backtracking Algorithm – Example Find path through maze Start at beginning of maze If at exit, return true Else for each step from current location – Recursively find path – Return with first successful step – Return false if all steps fail
  • 7. PS 7 Backtracking Algorithm – Example Color a map with no more than four colors If all countries have been colored return success Else for each color c of four colors and country n – If country n is not adjacent to a country that has been colored c Color country n with color c Recursively color country n+1 If successful, return success Return failure
  • 8. PS 8 Backtracking Start Success! Success! Failure Problem space consists of states (nodes) and actions (paths that lead to new states). When in a node can can only see paths to connected nodes If a node only leads to failure go back to its "parent" node. Try other alternatives. If these all lead to failure then more backtracking may be necessary.
  • 9. PS 9 Recursive Backtracking Pseudo code for recursive backtracking algorithms If at a solution, return success for( every possible choice from current state / node) Make that choice and take one step along path Use recursion to solve the problem for the new node / state If the recursive call succeeds, report the success to the next high level Back out of the current choice to restore the state at the beginning of the loop. Report failure
  • 10. PS 10 Backtracking Construct the state space tree: Root represents an initial state Nodes reflect specific choices made for a solution’s components. – Promising and nonpromising nodes – leaves Explore the state space tree using depth-first search “Prune” non-promising nodes dfs stops exploring subtree rooted at nodes leading to no solutions and... “backtracks” to its parent node
  • 11. PS 11 Example: The n-Queen problem Place n queens on an n by n chess board so that no two of them are on the same row, column, or diagonal
  • 12. PS 12 State Space Tree of the Four-queens Problem
  • 13. PS 13 The backtracking algorithm Backtracking is really quite simple--we “explore” each node, as follows: To “explore” node N: 1. If N is a goal node, return “success” 2. If N is a leaf node, return “failure” 3. For each child C of N, 3.1. Explore C 3.1.1. If C was successful, return “success” 4. Return “failure”
  • 14. PS 14 Exercises Continue the backtracking search for a solution to the four-queens problem to find the second solution to the problem. A trick to use: the board is symmetric, obtain another solution by reflections. Get a solution to the 5-queens problem found by the back-tracking algorithm? Can you (quickly) find at least 3 other solutions?
  • 15. PS 15 The m-Coloring Problem and Hamiltonian Problem 2-color 3-color Hamiltonian Circuit (use alphabet order to break the ties) c d a eb
  • 16. PS 16 Coloring a map You wish to color a map with not more than four colors red, yellow, green, blue Adjacent countries must be in different colors You don’t have enough information to choose colors Each choice leads to another set of choices One or more sequences of choices may (or may not) lead to a solution Many coloring problems can be solved with backtracking
  • 17. PS 17 Comments Backtracking provides the hope to solve some problem instances of nontrivial sizes by pruning non-promising branches of the state-space tree. The success of backtracking varies from problem to problem and from instance to instance. Backtracking possibly generates all possible candidates in an exponentially growing state-space tree.
  • 18. PS 18 Other Backtracking Problems * 8 Queens Knight's Tour Knapsack problem / Exhaustive Search Filling a knapsack. Given a choice of items with various weights and a limited carrying capacity find the optimal load out. 50 lb. knapsack. items are 1 40 lb, 1 32 lb. 2 22 lbs, 1 15 lb, 1 5 lb. A greedy algorithm would choose the 40 lb item first. Then the 5 lb. Load out = 45lb. Exhaustive search 22 + 22 + 5 = 49.
  • 19. PSUCS 311 – Design and Algorithms Analysis Dr. Mohamed Tounsi Branch and Bound
  • 20. PS 20 Branch and Bound ( B& B) An enhancement of backtracking Similarity –A state space tree is used to solve a problem. Difference –The branch-and-bound algorithm does not limit us to any particular way of traversing the tree. –Used only for optimization problems (since the backtracking algorithm requires the using of DFS traversal and is used for non- optimization problems.
  • 21. PS 21 Branch and Bound The idea: Set up a bounding function, which is used to compute a bound (for the value of the objective function) at a node on a state-space tree and determine if it is promising Promising (if the bound is better than the value of the best solution so far): expand beyond the node. Nonpromising (if the bound is no better than the value of the best solution so far): not expand beyond the node (pruning the state-space tree).
  • 22. PS 22 Traveling Salesman Problem Construct the state-space tree: A node = a vertex: a vertex in the graph. A node that is not a leaf represents all the tours that start with the path stored at that node; each leaf represents a tour (or non-promising node). Branch-and-bound: we need to determine a lower bound for each node – For example, to determine a lower bound for node [1, 2] means to determine a lower bound on the length of any tour that starts with edge 1—2. Expand each promising node, and stop when all the promising nodes have been expanded. During this procedure, prune all the nonpromising nodes. – Promising node: the node’s lower bound is less than current minimum tour length. – Non-promising node: the node’s lower bound is NO less than current minimum tour length.
  • 23. PS 23 Traveling Salesman Problem—Bounding Function 1 Because a tour must leave every vertex exactly once, a lower bound on the length of a tour is b (lower bound) minimum cost of leaving every vertex. The lower bound on the cost of leaving vertex v1 is given by the minimum of all the nonzero entries in row 1 of the adjacency matrix. … The lower bound on the cost of leaving vertex vn is given by the minimum of all the nonzero entries in row n of the adjacency matrix. Note: This is not to say that there is a tour with this length. Rather, it says that there can be no shorter tour. Assume that the tour starts with v1.
  • 24. PS 24 Traveling Salesman Problem—Bounding Function 2 Because every vertex must be entered and exited exactly once, a lower bound on the length of a tour is the sum of the minimum cost of entering and leaving every vertex. For a given edge (u, v), think of half of its weight as the exiting cost of u, and half of its weight as the entering cost of v. The total length of a tour = the total cost of visiting( entering and exiting) every vertex exactly once. The lower bound of the length of a tour = the lower bound of the total cost of visiting (entering and exiting ) every vertex exactly once. – Calculation: for each vertex, pick top two shortest adjacent edges (their sum divided by 2 is the lower bound of the total cost of entering and exiting the vertex); add up these summations for all the vertices. Assume that the tour starts with vertex a and that b is visited before c.

Editor's Notes

  1. Careful to draw the state-space by coloring vertices in alphabetical order. This way you get some actual “backtracking” – most small examples of graph coloring yield a solution so fast that it is hard to appreciate what is going on.
  2. Generate all n-bit binary strings.