Backtrack PPT

advertisement
CSC 172
DATA STRUCTURES
BACKTRACKING
Read Weiss 10.5
BACKTRACKING
 Backtracking
is a recursive strategy to explore
possible solutions.
possible solution – exhaustive search
 “Depth first search”
 “Branch & Bound”
 Every
BACKTRACKING METHODOLOGY



View picking a solution as a sequence of choices
For each choice, consider every option
recursively
Return the best solution found
BACKTRACKING
 Generic
enough to be applied to most problems.
 Probably still take exponential time
 Exact time analysis of backtracking algorithms can
be extremely difficult
 simpler
upperbounds that may not be tight are given.
Design Example
Design Example
Design Example
 The
“N-queens” problem
 Given an n-by-n checkerboard place n queens on
the board in such a way that no two queens are
mutually attacking each other.
 Issues:
 What
data structure?
 What algorithm?
Data
 Board
 Location
 Level
placeQueen(int [][] board, int x, int y) {
board[x][y]++;
for (int k=0; k<board[x].length;k++)
board[x][k]++ ;
removeQueen(int [][] board, int x, int y) {
board[x][y]--;
for (int k=0; k<board[x].length;k++)
board[x][k]--;
boolean nQueen(int [][] board,
int[]result, int level) {
if (level >= board.length) return true;
for (int k=0; k<board[level].length;k++){
if(board[level][k] <= 0) {
placeQueen(board,level,k);
result[level] = k;
if (nQueen(board,result,level+1))
return true ;
else //BACKTRACK
removeQueen(board,level,k);
}
}
return false ;
Download