Backtracking
Introduction Systematic way to do an exhaustive search Take advantage of pruning when possible
Turnpike Reconstruction Problem Given |D| distances, determine x coordinates for points lying on x-axis –|D|=N(N-1)/2 Easy to go from points to distances in O(N 2 ) – distances to points is worst-case exponential
Turnpike Reconstruction Problem N = 6 Should largest distance be placed on left or right side? –if 1 only, place –if both, choose 1 – if it does not lead to a solution, try the other –if neither, no solution to current configuration – backtrack D = {1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 8, 10} x 1 = 0x 6 = 10
Turnpike Reconstruction Problem D = {1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 8, 10} x 1 = 0x 6 = 10 x 1 =0 x 6 =10 x 5 =8 x 2 =3x 4 =7 x 3 =6x 2 =4x 3 =4x 4 =6 x 3 =5
TicTacToe Idea: for each possible move, determine outcome assuming player and computer will choose optimal subsequent moves Minimax strategy – human win = -1 and computer win = 1 – human tries to minimize value of play while computer tries to maximize value of play
TicTacToe findCompMove if(full) value = DRAW else if comp wins value = COMP_WIN else value = COMP_LOSS bestMove = 1 for (i 1->n) if empty place rval= findHumanMove unplace if rval > value value = rval bestMove = i findHumanMove if(full) value = DRAW else if comp wins value = COMP_LOSS else value = COMP_WIN bestMove = 1 for (i 1->n) if empty place rval= findCompMove unplace if rval < value value = rval bestMove = i
Game Tree Levels alternate min/max If solution is obvious – prune Example –44 (max) 44 (min) –44 (max) »27 »44 –68 »68 »C 40