CS100-RecursiveBacktracking1.pptx

advertisement
Please snarf the code for today’s class.
Then think about the famous 8-Queen’s Puzzle. The question is:
is there a way to arrange 8 queens on a (8x8) chessboard so that
no 2 queens can attack each other (queens can attack
horizontally, vertically, and diagonally)
The above board is 2 Queens short of a solution. Find the solution!
So how could we solve this problem
computationally?
1. I could solve this problem with a couple of
carefully constructed loops
2. I think recursion is needed to solve this
problem
3. I think stacks and queues are needed to solve
this problem
4. I think some new secret technique is needed
that I’m guessing will be revealed today
The Basic Recursive Backtracking
Solution
• I start at a particular state, where I have to make a
decision from a list of options
• For each option:
– Try deciding on that option
– UPDATE THE STATE
– Recursively call myself to try all subsequent paths from
that point
– If I find a solution…do something (maybe return, maybe
increment a counter)
– UNDO the state change I just made
• At this point I’ve done everything I can do in this state
Recursive Backtracking
1. You will be able to describe the basic
approach of recursive backtracking
2. We will look at a very simple recursive
backtracking problem.
3. You will solve a slightly more complicated
recursive backtracking problem
4. We will go over a solution to the n-queens
problem, and you’ll edit the solution
• Go to codingBat.com/java/Recursion-2
• Solve groupNoAdj
• If you finish that one, try and solve splitArray
(this can be solved using a simple for loop and
groupSum or by using a separate helper
function)
• Put the code into a file in the code you snarfed
for today – you’ll submit that directory via
ambient
Modify the code of 8-Queens
• First figure out how to modify the code to solve
the 8 Rooks problem (Rooks can only attack
horizontally and vertically, not diagonally). Get
your code working and then change it back to
queens when you’re done.
• Modify the code to count the number of
solutions to the 8 Queens problem. There should
be 92 solutions.
• When you’re finished, submit the result via
ambient
Recursive Backtracking
1. You will be able to describe the basic
approach of recursive backtracking
2. We will look at a very simple recursive
backtracking problem.
3. You will solve a slightly more complicated
recursive backtracking problem
4. We will go over a solution to the n-queens
problem, and you’ll edit the solution
Download