Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 172 DATA STRUCTURES.

Similar presentations


Presentation on theme: "CSC 172 DATA STRUCTURES."— Presentation transcript:

1 CSC 172 DATA STRUCTURES

2 BACKTRACKING Read Weiss 10.5

3 BACKTRACKING Backtracking is a recursive strategy to explore possible solutions. Every possible solution – exhaustive search “Depth first search” “Branch & Bound”

4 BACKTRACKING METHODOLOGY
View picking a solution as a sequence of choices For each choice, consider every option recursively Return the best solution found

5 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.

6 Design Example

7 Design Example

8 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?

9 Data Board Location Level

10 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]--; board[x][k]--;

11 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 ;

12


Download ppt "CSC 172 DATA STRUCTURES."

Similar presentations


Ads by Google