120 likes | 140 Views
Backtracking is a recursive approach to finding all possible solutions through exhaustive search. It involves making a sequence of choices and exploring each option recursively to find the best solution. While generic, backtracking can be applied to various problems, though it may still take exponential time.
E N D
BACKTRACKING Backtracking is a recursive strategy to explore possible solutions. Every possible solution – exhaustive search “Depth first search” “Branch & Bound”
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 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 ; }