21 Recursion and Backtracking
-
Upload
madhurljit -
Category
Documents
-
view
231 -
download
0
Transcript of 21 Recursion and Backtracking
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 1/25
3/5/09
1
Intermediate / Advanced
Programming
Recursion and Backtracking
Lynn Robert Carter 2009-03-03
© Copyright 2009, Lynn Robert Carter
Intermediate/Advanced ProgrammingRecursion and Backtracking
Agenda
N Queens
+ Finding solutions
+ Backtracking
+ The N Queens solution
2
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 2/25
3/5/09
2
Intermediate/Advanced ProgrammingRecursion and Backtracking
The N Queens Puzzle
+ Consider a board, like a chess board, but
one where you can specify the board size
+ How many chess queens can be placed
on this “board” so that no queen can “take”
another?+ How many different placements of queens
can be made for a given sized board?
3
Intermediate/Advanced ProgrammingRecursion and Backtracking
A board of size 5
4
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 3/25
3/5/09
3
Intermediate/Advanced ProgrammingRecursion and Backtracking
What does “take” mean?
+ In chess a piece “takes” another piece
when it can move to the same square as
the piece it is going to take
+ The various pieces on a chess board
move in very different ways+ Some pieces, such are rooks (castles) can
move all the way across the board, but
only up, down, left, or right
5
Intermediate/Advanced ProgrammingRecursion and Backtracking
How does a Queen move?
6
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 4/25
3/5/09
4
Intermediate/Advanced ProgrammingRecursion and Backtracking
The moves of a Queen
7
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Safe places for a second Queen
8
♕
♕ ♕
♕
♕
♕♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 5/25
3/5/09
5
Intermediate/Advanced ProgrammingRecursion and Backtracking
Agenda
N Queens
Finding solutions
+ Backtracking
+ The N Queens solution
9
Intermediate/Advanced ProgrammingRecursion and Backtracking
Finding solutions
+ Start in the first row, we
have a choice of five
possible moves
+ Any of these five choices
could lead to a solution
+ To move forward, we
have to choose one and
then see if that can lead
to a solution
10
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 6/25
3/5/09
6
Intermediate/Advanced ProgrammingRecursion and Backtracking
The first move
+ To be systematic, pick the
first one; place a queen in
the first square
+ We know than no other
queen can be in that row
+ So start with the second
row and see which
squares are “safe”
11
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible safe places
+ The first column is not
safe
+ The second square in the
second row is not safe
+ All of the others in the row
are safe
+ Let’s use the first one
12
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 7/25
3/5/09
7
Intermediate/Advanced ProgrammingRecursion and Backtracking
Examine row three
+ Which of the squares in
row three are “safe”?
13
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Examine row three
+ The only “safe” square in
this situation is the right
most square
+ So place a queen there
14
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 8/25
3/5/09
8
Intermediate/Advanced ProgrammingRecursion and Backtracking
Examine row four
+ Where are the safe
squares in row four?
15
♕
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Examine row four
+ There is just one possible
square for the fourth row
+ Once again, place the
next queen there!
16
♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 9/25
3/5/09
9
Intermediate/Advanced ProgrammingRecursion and Backtracking
Examine the last row
+ Once again, there is only
one choice
17
♕
♕
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
A solution
+ Using this process, we
have found a solution
+ How many more solutions
are possible?
18
♕
♕
♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 10/25
3/5/09
10
Intermediate/Advanced ProgrammingRecursion and Backtracking
Agenda
N Queens
Finding solutions
Backtracking
+ The N Queens solution
19
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens
+ Consider the 4 Queens case
+ There are four possible first
moves
20
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 11/25
3/5/09
11
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 2 choice
+ Start with a Queen in the
first row and first column
+ There are just two possible
choices for the second row
+ Let’s pick the first one
21
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 2
+ Given this sized board and
these two queens, where
can a queen go for row 3?
22
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 12/25
3/5/09
12
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 3
+ There is no “safe” move in
this situation, so be have to
back up and try a different
choice
+ This “backing up” is known
as “backtracking”
+ So, let’s back up to the most
recent point where we had a
choice, the choice in row 2
23
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Back up to row two
+ We know that the first of
these two choices does not
lead to a solution
+ Let’s try the second of the
two choices
24
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 13/25
3/5/09
13
Intermediate/Advanced ProgrammingRecursion and Backtracking
A second try at row three
+ With queens positioned as
shown here, where are the
possible “safe” moves in row
three?
25
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible row three moves
+ With queens positioned as
shown here, there is just
one possible “safe” move,
so let’s take it
26
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 14/25
3/5/09
14
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible row four moves
+ Where are the “safe” moves
in row four?
27
♕
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Another failure
+ There are no safe moves
here, so… we have to back
track again
28
♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 15/25
3/5/09
15
Intermediate/Advanced ProgrammingRecursion and Backtracking
Once again at row two
+ Now we know that neither of
the two choices for row 2
will lead us to a solution
+ Therefore, we must back up
to row 1 and try a different
choice there
29
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
Backup all the way to row 1
+ We now know that it is not
possible for 4 Queens to
have a solution with a queen
in the first row and first
column
+ Let’s try the queen in the
first row and second column
30
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 16/25
3/5/09
16
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 2 choice
+ With a queen in this position
in the first row, there is only
one choice for row 2
+ So, let’s make that move
31
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 3 choice
+ Queens in these positions
for the first two rows means
that there is again just one
choice for row three
+ So, let’s make that move
32
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 17/25
3/5/09
17
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens row 4 choice
+ Queens in these positions
for the first three rows
means once again just one
choice is possible
+ So, let’s make that move
33
♕
♕
♕
Intermediate/Advanced ProgrammingRecursion and Backtracking
4 Queens solution
+ A queen in the first row and
second column leads to a
solution
+ How many more solutions
are possible?
34
♕
♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 18/25
3/5/09
18
Intermediate/Advanced ProgrammingRecursion and Backtracking
Number of possible solutions
+ We know about two of the
choices in the first row
+ What is your intuition about
the other two positions?
35
Intermediate/Advanced ProgrammingRecursion and Backtracking
A tree of possible solutions
36
♕ ♕ ♕ ♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕
♕ ♕ ♕ ♕
12 more
not shown
60 more
not shown
252 more
not shown
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 19/25
3/5/09
19
Intermediate/Advanced ProgrammingRecursion and Backtracking
A solution strategy
+ Build a tree of all possible valid queen
placements
+ Traverse the whole tree
+ Whenever there is a board where the
number of queens is equal the number of rows in the board, add that board to a
collection of solutions
37
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible valid placements?
+ Assume you are given a valid board and a
row number where you are to try to place
as many queens as possible
+ How can you do this?
38
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 20/25
3/5/09
20
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible valid placements
+ Perform a loop that iterates once for each
possible placement in the new row using
the index col
+ Make a temporary copy of the board
+ Try to place the queen in the columnsspecified by col
+ If that placement is valid, use it to try to place
queens in the rest of the rows (recursively)
39
Intermediate/Advanced ProgrammingRecursion and Backtracking
Possible placement example
40
♕ ♕ ♕ ♕
♕
♕
♕
♕
♕
♕
♕
♕
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 21/25
3/5/09
21
Intermediate/Advanced ProgrammingRecursion and Backtracking
addQueen
41
/*** Method to add a Queen to the board * @param b The Board * @param rowNum The starting row number to try to add the queen* * @return The board after placing the Queen, if possible else null*/public Board addQueen(Board b, int rowNum) {// base case: number of Queens on the board is equal to the board sizeif(b.numQueens() == b.getSize()) return b;
for(int x =0; x < b.getSize(); x++){ Board tempBoard = new Board(b); // try to place the queen in the board at column x within row, rowNum if(tempBoard.place(new Board.Position(rowNum, x))){ // If it was added successfully // recursively try adding a queen into the next row Board nextBoard = addQueen(tempBoard, rowNum+1); // If it comes back null, no solution is possible if(nextBoard != null) // The board is not null, so this is a solution return nextBoard; }}return null;
}
Intermediate/Advanced ProgrammingRecursion and Backtracking
getAllSolutions
42
/** * Method to get all possible solutions to the Queens problem* * @param b The board to place the Queens at* @param c All possible boards* @param rowNum The initial row number to start placing queens*/public void getAllSolutions(Board b, Collection<Board> c, int rowNum){
if(rowNum < b.getSize()){ for(int x =0; x< b.getSize(); x++){ Board tempBoard = new Board(b); if(tempBoard.place(new Board.Position(rowNum, x))){ // a queen is placed at that row // recursively call the method on the next row getAllSolutions(tempBoard, c, rowNum+1); } } // getting here means that we have run past the end of the row // so we return without adding any more boards to the collection return;}// add the solved board to the Collection of boards// this only happens when rowNum >= b.getSize()c.add(b);
}
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 22/25
3/5/09
22
Intermediate/Advanced ProgrammingRecursion and Backtracking
The Class Design of NQueens
+ The program consists of
+ A class that defines the board (Board)
+ A class that solve the problem (NQueens)
+ A class that implements a Swing GUI window
(NQueensSwing)
+ A mainline class for the Swing version of the
puzzle solver (NQueensGUI)
+ A mainline class for a text version (Driver)
43
Intermediate/Advanced ProgrammingRecursion and Backtracking
The NQueen Board-1
44
public class Board {protected enum BoardState implements Cloneable { UNTHREATENED , THREATENED , QUEEN };protected BoardState[][] board;private int n;private int numQueens;public static class Position { int x = 0, y = 0; public Position(int i, int j) { x = i; y = j; } public boolean equals(Position p) { return x == p.x && y == p.y; }}public int getSize(){ return this.n;}
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 23/25
3/5/09
23
Intermediate/Advanced ProgrammingRecursion and Backtracking
The NQueen Board-2
45
/** * Constructs an empty board sizeXsize * * Complains if you attempt to construct a negative board Boards of size 0 * are allowed */public Board(int size) { if (size < 0) { System.out .println("Negative boards are not allowed."); return; }
n = size; numQueens = 0; board = new BoardState[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) board[i][j] = BoardState.UNTHREATENED ;}public Board(Board b) { board = new BoardState[b.n][b.n]; for (int i = 0; i < b.n; i++) for (int j = 0; j < b.n; j++) board[i][j]=b.board[i][j]; n = b.n; numQueens = b.numQueens;}
Intermediate/Advanced ProgrammingRecursion and Backtracking
isThreatened and more
46
/*** Determines if a position can be reached in one or zero moves by any of* the queens currently on the board* * @param p* the position to determine the state of* @return true if Position p is being threatened*/public boolean isThreatened(Position p) {return board[p.x][p.y] != BoardState.UNTHREATENED ;}/*** accessor for the number of queens currently placed on the board*/public int numQueens() {return numQueens;}/*** returns true if the maximum number of queens have been placed.*/public boolean done() {if (n < 1 || n == 2 || n == 3) return (numQueens == 0);return (numQueens == n);}
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 24/25
3/5/09
24
Intermediate/Advanced ProgrammingRecursion and Backtracking
place
47
/*** Places a queen on the board at Position P if that is an empty* unthreatened place* * @param p* the position to place the queen in* * @return true if placement is sucsessful*/public boolean place(Position p) {if (board[p.x][p.y] != BoardState.UNTHREATENED )return false;
// mark the row and col as threatenedfor (int i = 0; i < n; i++) { board[p.x][i] = BoardState.THREATENED ; board[i][p.y] = BoardState.THREATENED ;}// mark the diagonals as threatenedfor (int x = p.x, y = p.y; x < n && y < n; x++, y++) board[x][y] = BoardState.THREATENED ;for (int x = p.x, y = p.y; x >= 0 && y >= 0; x--, y--) board[x][y] = BoardState.THREATENED ;for (int x = p.x, y = p.y; x >= 0 && y < n; x--, y++) board[x][y] = BoardState.THREATENED ;for (int x = p.x, y = p.y; x < n && y >= 0; x++, y--) board[x][y] = BoardState.THREATENED ;board[p.x][p.y] = BoardState.QUEEN ;numQueens++;return true;
}
Intermediate/Advanced ProgrammingRecursion and Backtracking
Agenda
N Queens
Finding solutions
Backtracking
The N Queens solution
48
8/7/2019 21 Recursion and Backtracking
http://slidepdf.com/reader/full/21-recursion-and-backtracking 25/25
3/5/09
25
Intermediate/Advanced ProgrammingRecursion and Backtracking
A sample solution
+ Download the NQueens archive from the
blackboard and get it to work
+ A solution written by Hatem Alismail
+ Study the solution and be able to answer
some questions about this code
49
Intermediate / Advanced
Programming
Recursion and Backtracking
Lynn Robert Carter 2009-03-03
© Copyright 2009, Lynn Robert Carter