SlideShare a Scribd company logo
1 of 13
Backtracking(DAA)
1 Jaydeep Patil (AISSMS IOIT)
Backtracking
 Backtracking is a technique used to solve problems
with a large search space, by systematically trying
and eliminating possibilities.
 A standard example of backtracking would be going
through a maze.
 At some point in a maze, you might have two options
of which direction to go:
Portion A
PortionB
2 Jaydeep Patil (AISSMS IOIT)
Backtracking
Portion B
PortionA
 One strategy would
be to try going through
Portion A of the maze.
 If you get stuck before
you find your way out,
then you "backtrack"
to the junction.
 At this point in time you
know that Portion A
will NOT lead you out
of the maze,
 so you then start
searching in Portion B
3 Jaydeep Patil (AISSMS IOIT)
Backtracking
 Clearly, at a single junction
you could have even more
than 2 choices.
 The backtracking strategy
says to try each choice,
one after the other,
 if you ever get stuck,
"backtrack" to the
junction and try the next
choice.
 If you try all choices and
never found a way out,
B
C
A
4 Jaydeep Patil (AISSMS IOIT)
Backtracking – Eight Queens
Problem
 Find an arrangement of 8
queens on a single chess
board such that no two
queens are attacking one
another.
 In chess, queens can move
all the way down any row,
column or diagonal (so long
as no pieces are in the
way).
 Due to the first two
restrictions, it's clear that
each row and column of the5 Jaydeep Patil (AISSMS IOIT)
Backtracking – Eight Queens
Problem
 The backtracking strategy is
as follows:
1) Place a queen on the first
available square in row 1.
2) Move onto the next row,
placing a queen on the first
available square there (that
doesn't conflict with the
previously placed queens).
3) Continue in this fashion until
either:
a) you have solved the problem,
or
b) you get stuck.
 When you get stuck,
remove the queens that got
Animated Example:
http://www.hbmeyer.de/backtrac
k/achtdamen/eight.htm#up
Q
Q
Q
Q
Q Q
Continue…
6 Jaydeep Patil (AISSMS IOIT)
Backtracking – Eight Queens
Problem
 When we carry out backtracking, an easy way
to visualize what is going on is a tree that
shows all the different possibilities that have
been tried.
 On the board we will show a visual
representation of solving the 4 Queens problem
(placing 4 queens on a 4x4 board where no two
attack one another).
7 Jaydeep Patil (AISSMS IOIT)
Backtracking – Eight Queens
Problem
 The neat thing about coding up backtracking, is
that it can be done recursively, without having to
do all the bookkeeping at once.
 Instead, the stack or recursive calls does most of
the bookkeeping
 (ie, keeping track of which queens we've placed,
and which combinations we've tried so far, etc.)
8 Jaydeep Patil (AISSMS IOIT)
void solveItRec(int perm[], int location, struct onesquare usedList[]) {
if (location == SIZE) {
printSol(perm);
}
for (int i=0; i<SIZE; i++) {
if (usedList[i] == false) {
if (!conflict(perm, location, i)) {
perm[location] = i;
usedList[i] = true;
solveItRec(perm, location+1, usedList);
usedList[i] = false;
}
}
}
}
perm[] - stores a valid permutation of queens from index 0 to location-1.
location – the column we are placing the next queen
usedList[] – keeps track of the rows in which the queens have already been placed.
Found a solution to the problem, so print it!
Loop through possible rows to place this queen.
Only try this row if it hasn’t been used
Check if this position conflicts with any
previous queens on the diagonal
1) mark the queen in this row
2) mark the row as used
3) solve the next column
location recursively
4) un-mark the row as used, so
we can get ALL possible valid
solutions.
9 Jaydeep Patil (AISSMS IOIT)
Backtracking – 8 queens problem - Analysis
 Another possible brute-force algorithm is generate the
permutations of the numbers 1 through 8 (of which there are
8! = 40,320),
 and uses the elements of each permutation as indices to place a
queen on each row.
 Then it rejects those boards with diagonal attacking positions.
 The backtracking algorithm, is a slight improvement on the
permutation method,
 constructs the search tree by considering one row of the board at
a time, eliminating most non-solution board positions at a very
early stage in their construction.
 Because it rejects row and diagonal attacks even on incomplete
boards, it examines only 15,720 possible queen placements.
 A further improvement which examines only 5,508 possible
queen placements is to combine the permutation based
method with the early pruning method:
 The permutations are generated depth-first, and the search space
is pruned if the partial permutation produces a diagonal attack
10 Jaydeep Patil (AISSMS IOIT)
Sudoku and Backtracking
 Another common puzzle that can be solved by
backtracking is a Sudoku puzzle.
 The basic idea behind the solution is as follows:
1) Scan the board to look for an empty square that could
take on the fewest possible values based on the
simple game constraints.
2) If you find a square that can only be one possible
value, fill it in with that one value and continue the
algorithm.
3) If no such square exists, place one of the possible
numbers for that square in the number and repeat the
process.
4) If you ever get stuck, erase the last number placed
and see if there are other possible choices for that
slot and try those next.
11 Jaydeep Patil (AISSMS IOIT)
Mazes and Backtracking
 A final example of something that can be solved
using backtracking is a maze.
 From your start point, you will iterate through each
possible starting move.
 From there, you recursively move forward.
 If you ever get stuck, the recursion takes you back to
where you were, and you try the next possible move.
 In dealing with a maze, to make sure you don't try
too many possibilities,
 one should mark which locations in the maze have
been visited already so that no location in the maze
gets visited twice.
 (If a place has already been visited, there is no point12 Jaydeep Patil (AISSMS IOIT)
Backtracking – optional homework
problem
 Determine how many solutions there are to the 5
queens problem.
 Demonstrate backtracking for at least 2 solutions to
the 5 queens problem, by tracing through the
decision tree as shown in class.
13 Jaydeep Patil (AISSMS IOIT)

More Related Content

What's hot

daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy methodhodcsencet
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treeoneous
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardAnimesh Chaturvedi
 
Lecture 11 Informed Search
Lecture 11 Informed SearchLecture 11 Informed Search
Lecture 11 Informed SearchHema Kashyap
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmHoneyChintal
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithmsRajendran
 
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 boundAbhishek Singh
 
Open addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingOpen addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingSangeethaSasi1
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problemsJyotsna Suryadevara
 
Temporal difference learning
Temporal difference learningTemporal difference learning
Temporal difference learningJie-Han Chen
 

What's hot (20)

daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
Lecture 11 Informed Search
Lecture 11 Informed SearchLecture 11 Informed Search
Lecture 11 Informed Search
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
Hamiltonian path
Hamiltonian pathHamiltonian path
Hamiltonian path
 
Hill climbing algorithm
Hill climbing algorithmHill climbing algorithm
Hill climbing algorithm
 
Knapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithmKnapsack problem algorithm, greedy algorithm
Knapsack problem algorithm, greedy algorithm
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
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
 
Open addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingOpen addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashing
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Np complete
Np completeNp complete
Np complete
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
 
Temporal difference learning
Temporal difference learningTemporal difference learning
Temporal difference learning
 

Similar to Backtracking

Branch and bound
Branch and boundBranch and bound
Branch and boundAcad
 
Back tracking and branch and bound class 20
Back tracking and branch and bound class 20Back tracking and branch and bound class 20
Back tracking and branch and bound class 20Kumar
 
Backtrack search-algorithm
Backtrack search-algorithmBacktrack search-algorithm
Backtrack search-algorithmRuchika Sinha
 
Backtracking Basics.pptx
Backtracking Basics.pptxBacktracking Basics.pptx
Backtracking Basics.pptxsunidhi740916
 
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfRequirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfalphaagenciesindia
 
Backtrack-search-algorithm (2).pptx
Backtrack-search-algorithm (2).pptxBacktrack-search-algorithm (2).pptx
Backtrack-search-algorithm (2).pptxAnLPhc1
 
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...SOURAV DAS
 
(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 aiRadhika Srinivasan
 
Queue- 8 Queen
Queue- 8 QueenQueue- 8 Queen
Queue- 8 QueenHa Ninh
 
380 Final Paper Battleship Optimization
380 Final Paper Battleship Optimization380 Final Paper Battleship Optimization
380 Final Paper Battleship OptimizationSteve Myrick
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfShiwani Gupta
 
5.5 back track
5.5 back track5.5 back track
5.5 back trackKrish_ver2
 
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjekAIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjekpavan402055
 
4 10 Notes B
4 10 Notes B4 10 Notes B
4 10 Notes Bmbetzel
 
Lec10-CS110 Computational Engineering
Lec10-CS110 Computational EngineeringLec10-CS110 Computational Engineering
Lec10-CS110 Computational EngineeringSri Harsha Pamu
 

Similar to Backtracking (20)

Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Back tracking and branch and bound class 20
Back tracking and branch and bound class 20Back tracking and branch and bound class 20
Back tracking and branch and bound class 20
 
Backtrack search-algorithm
Backtrack search-algorithmBacktrack search-algorithm
Backtrack search-algorithm
 
Backtracking Basics.pptx
Backtracking Basics.pptxBacktracking Basics.pptx
Backtracking Basics.pptx
 
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfRequirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
 
Backtrack-search-algorithm (2).pptx
Backtrack-search-algorithm (2).pptxBacktrack-search-algorithm (2).pptx
Backtrack-search-algorithm (2).pptx
 
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...
INTERVIEW TIPS HOW TO TACKLE SOFT SKILLS INTELLIGENT AND SMART ANSWERS BY SOU...
 
(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai
 
Queue- 8 Queen
Queue- 8 QueenQueue- 8 Queen
Queue- 8 Queen
 
380 Final Paper Battleship Optimization
380 Final Paper Battleship Optimization380 Final Paper Battleship Optimization
380 Final Paper Battleship Optimization
 
module5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdfmodule5_backtrackingnbranchnbound_2022.pdf
module5_backtrackingnbranchnbound_2022.pdf
 
Back tracking
Back trackingBack tracking
Back tracking
 
5.5 back track
5.5 back track5.5 back track
5.5 back track
 
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjekAIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
 
Parallel search
Parallel searchParallel search
Parallel search
 
Matrices
MatricesMatrices
Matrices
 
4 10 Notes B
4 10 Notes B4 10 Notes B
4 10 Notes B
 
Lec10-CS110 Computational Engineering
Lec10-CS110 Computational EngineeringLec10-CS110 Computational Engineering
Lec10-CS110 Computational Engineering
 
groovy & grails - lecture 8
groovy & grails - lecture 8groovy & grails - lecture 8
groovy & grails - lecture 8
 
Sudoku solver
Sudoku solverSudoku solver
Sudoku solver
 

Recently uploaded

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 

Recently uploaded (20)

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 

Backtracking

  • 2. Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating possibilities.  A standard example of backtracking would be going through a maze.  At some point in a maze, you might have two options of which direction to go: Portion A PortionB 2 Jaydeep Patil (AISSMS IOIT)
  • 3. Backtracking Portion B PortionA  One strategy would be to try going through Portion A of the maze.  If you get stuck before you find your way out, then you "backtrack" to the junction.  At this point in time you know that Portion A will NOT lead you out of the maze,  so you then start searching in Portion B 3 Jaydeep Patil (AISSMS IOIT)
  • 4. Backtracking  Clearly, at a single junction you could have even more than 2 choices.  The backtracking strategy says to try each choice, one after the other,  if you ever get stuck, "backtrack" to the junction and try the next choice.  If you try all choices and never found a way out, B C A 4 Jaydeep Patil (AISSMS IOIT)
  • 5. Backtracking – Eight Queens Problem  Find an arrangement of 8 queens on a single chess board such that no two queens are attacking one another.  In chess, queens can move all the way down any row, column or diagonal (so long as no pieces are in the way).  Due to the first two restrictions, it's clear that each row and column of the5 Jaydeep Patil (AISSMS IOIT)
  • 6. Backtracking – Eight Queens Problem  The backtracking strategy is as follows: 1) Place a queen on the first available square in row 1. 2) Move onto the next row, placing a queen on the first available square there (that doesn't conflict with the previously placed queens). 3) Continue in this fashion until either: a) you have solved the problem, or b) you get stuck.  When you get stuck, remove the queens that got Animated Example: http://www.hbmeyer.de/backtrac k/achtdamen/eight.htm#up Q Q Q Q Q Q Continue… 6 Jaydeep Patil (AISSMS IOIT)
  • 7. Backtracking – Eight Queens Problem  When we carry out backtracking, an easy way to visualize what is going on is a tree that shows all the different possibilities that have been tried.  On the board we will show a visual representation of solving the 4 Queens problem (placing 4 queens on a 4x4 board where no two attack one another). 7 Jaydeep Patil (AISSMS IOIT)
  • 8. Backtracking – Eight Queens Problem  The neat thing about coding up backtracking, is that it can be done recursively, without having to do all the bookkeeping at once.  Instead, the stack or recursive calls does most of the bookkeeping  (ie, keeping track of which queens we've placed, and which combinations we've tried so far, etc.) 8 Jaydeep Patil (AISSMS IOIT)
  • 9. void solveItRec(int perm[], int location, struct onesquare usedList[]) { if (location == SIZE) { printSol(perm); } for (int i=0; i<SIZE; i++) { if (usedList[i] == false) { if (!conflict(perm, location, i)) { perm[location] = i; usedList[i] = true; solveItRec(perm, location+1, usedList); usedList[i] = false; } } } } perm[] - stores a valid permutation of queens from index 0 to location-1. location – the column we are placing the next queen usedList[] – keeps track of the rows in which the queens have already been placed. Found a solution to the problem, so print it! Loop through possible rows to place this queen. Only try this row if it hasn’t been used Check if this position conflicts with any previous queens on the diagonal 1) mark the queen in this row 2) mark the row as used 3) solve the next column location recursively 4) un-mark the row as used, so we can get ALL possible valid solutions. 9 Jaydeep Patil (AISSMS IOIT)
  • 10. Backtracking – 8 queens problem - Analysis  Another possible brute-force algorithm is generate the permutations of the numbers 1 through 8 (of which there are 8! = 40,320),  and uses the elements of each permutation as indices to place a queen on each row.  Then it rejects those boards with diagonal attacking positions.  The backtracking algorithm, is a slight improvement on the permutation method,  constructs the search tree by considering one row of the board at a time, eliminating most non-solution board positions at a very early stage in their construction.  Because it rejects row and diagonal attacks even on incomplete boards, it examines only 15,720 possible queen placements.  A further improvement which examines only 5,508 possible queen placements is to combine the permutation based method with the early pruning method:  The permutations are generated depth-first, and the search space is pruned if the partial permutation produces a diagonal attack 10 Jaydeep Patil (AISSMS IOIT)
  • 11. Sudoku and Backtracking  Another common puzzle that can be solved by backtracking is a Sudoku puzzle.  The basic idea behind the solution is as follows: 1) Scan the board to look for an empty square that could take on the fewest possible values based on the simple game constraints. 2) If you find a square that can only be one possible value, fill it in with that one value and continue the algorithm. 3) If no such square exists, place one of the possible numbers for that square in the number and repeat the process. 4) If you ever get stuck, erase the last number placed and see if there are other possible choices for that slot and try those next. 11 Jaydeep Patil (AISSMS IOIT)
  • 12. Mazes and Backtracking  A final example of something that can be solved using backtracking is a maze.  From your start point, you will iterate through each possible starting move.  From there, you recursively move forward.  If you ever get stuck, the recursion takes you back to where you were, and you try the next possible move.  In dealing with a maze, to make sure you don't try too many possibilities,  one should mark which locations in the maze have been visited already so that no location in the maze gets visited twice.  (If a place has already been visited, there is no point12 Jaydeep Patil (AISSMS IOIT)
  • 13. Backtracking – optional homework problem  Determine how many solutions there are to the 5 queens problem.  Demonstrate backtracking for at least 2 solutions to the 5 queens problem, by tracing through the decision tree as shown in class. 13 Jaydeep Patil (AISSMS IOIT)