Compsci 201 Backtracking Owen Astrachan olacs duke edu
Compsci 201 Backtracking Owen Astrachan ola@cs. duke. edu November 9, 2018 11/9/2018 Compsci 201, Fall 2018, Backtracking 1
S is for … • Stack • Last in, First Out, source of overflow! • Software • Joys and sorrows, eating the world 11/9/2018 Compsci 201, Fall 2018, Backtracking 2
Plan for Today • Backtracking: try, retry, try again • Paradigm for searching and much more • Demonstration of recursion • Lead-in to Percolation assignment and APTs • Community hygiene • How we can all succeed, thrive, move forward 11/9/2018 Compsci 201, Fall 2018, Backtracking 3
Flood Fill, Blob Count https: //github. com/astrachano/backtracking-fall 18 11/9/2018 Compsci 201, Fall 2018, Backtracking 4
Applications • Using draw/paint program, fill a region • Redeye removal • Give image partially transparent background • Finding edges or blobs in image processing 11/9/2018 Compsci 201, Fall 2018, Backtracking 5
Blob Counting Ideas • How do I count “my region” or “my blob” size? • Ask my neighbors their size • Add +1 to their result • Avoid double-counting! • Colors indicate calls • White calls green • Green calls tan and gray • Gray calls mustard, … 11/9/2018 Compsci 201, Fall 2018, Backtracking 6
Bookkeeping Details • Blobs marked with ‘*’ – aka asterisk • We fill or mark cells when counting • Filling avoids counting cells twice • Filling allows for visualization as well • Blob. Model. blob. Fill method: (row, col) for start • look. For character, e. g. , ‘*’ • fill. With character, e. g. , ‘ 1’ or ‘ 7’ or … • If blob not big enough? Erase: look. For = fill. With 11/9/2018 Compsci 201, Fall 2018, Backtracking 7
Two Stage Analysis • Before looking for blobs? Make a copy of data • Data stored in two-dimensional array int[][] • char values can be stored as int values • Look at every possible blob starting location • If it's a blob? Mark with number • If it's not a blob? Erase any markings • There is a minimal size, erasing cleans up 11/9/2018 Compsci 201, Fall 2018, Backtracking 8
Lookfor Blobs Everywhere • Two parameters in each call to blob. Fill look. For 11/9/2018 Compsci 201, Fall 2018, Backtracking fill. With 9
Blobs starting at (row, col) • Ask each of four neighbors for their blob-size • Add me, +1, to what they report back 11/9/2018 Compsci 201, Fall 2018, Backtracking 10
When does process stop? • If (row, col) is not in bounds? Do nothing • If grid[row][col] != look. For? Do nothing • Otherwise (what do we know here? ) • In bounds AND looking for ‘*’ for example • Look at horizontal and vertical neighbors • Use results of recursive calls to create return 11/9/2018 Compsci 201, Fall 2018, Backtracking 11
blob. Fill(row, col) • Returns a value, make sure value used • Both in original calls • And in recursive calls • How do we know this will terminate? • Each recursive call “marks” a cell • my. Grid[row][col] = fill. With • Unless fill. With == look. For, not infinite! 11/9/2018 Compsci 201, Fall 2018, Backtracking 12
WOTO for Blobs http: //bit. ly/201 fall 18 -nov 9 -1 11/9/2018 Compsci 201, Fall 2018, Backtracking 13
Sir Tim Berners-Lee • Invented the Web, http • Not the Internet • Turing award 2016 One way to think about the magnitude of the changes to come is to think about how you went about your business before powerful Web search engines. You probably wouldn't have imagined that a world of answers would be available to you in under a second. The next set of advances will have a different effect, but similar in magnitude. http: //www. cnn. com/2005/TECH/internet/08/30/tim. berners. lee/ 11/9/2018 Compsci 201, Fall 2018, Backtracking 14
Level-Order aka Breadth-First • We saw level-order tree traversal using Queue • From top, then all children (one-away) • Then their children (two-away), then … 11/9/2018 Compsci 201, Fall 2018, Backtracking 15
Use BFS instead of recursion https: //github. com/astrachano/backtrackingfall 18 • Details: queue, parallel grid [][], row. Delta • Easier • Similar 11/9/2018 Compsci 201, Fall 2018, Backtracking 16
How to search 8 neighbors? • We need to make 8 recursive calls • W, N, NE, E, S, SW • See coding “trick” below int[] rd = {0, -1, -1, 0, 1, 1, 1}; int[] cd = {-1, 0, 1, 1, 1, 0, -1}; for(int d = 0; d < rd. length; d+= 1){ int nr = row + rd[d]; int nc = col + cd[d]; size += blob. Fill(nr, nc, …) } 11/9/2018 Compsci 201, Fall 2018, Backtracking 17
Backtracking and Blob Fill • Explore a move (blob fill) if it works? Fabulous! • If it does not work? Undo the move, try again • Similar to Sudoku solving? Crossword puzzles? • Tentatively try number of word, follow through • May need to undo and try alternative 11/9/2018 Compsci 201, Fall 2018, Backtracking 18
Exhaustive Search • Can explore every possible move in tic-tactoe • Cannot explore every possible move in chess • Brute-force doesn't work • Be smart, try move? Then undo, try another • Backtracking in search tree • Smart pruning 11/9/2018 Compsci 201, Fall 2018, Backtracking 19
N-Queens: Know History • Can we place N queens on Nx. N board so no queen attacks another • 4 x 4 or 8 x 8 or … 11/9/2018 Compsci 201, Fall 2018, Backtracking 20
Nqueen Concepts • For each column c in [0. . N) • Try to place queen in each row of column c • grid[r][c] ok? Place queen, try c+1 • If not ok? Or Doesn't work? Try next row, r+1 • When have all queens been placed? • If c == N and success? Done! • Can't do column c? return false, c-1 continues 11/9/2018 Compsci 201, Fall 2018, Backtracking 21
Code for Nqueens Backtracking • Done when c == N • Place queens, recurse, unplace and try again • Return true • All placed • Recursive • Use my. Board • Track moves 11/9/2018 Compsci 201, Fall 2018, Backtracking 22
Backtracking Summary • Enumerate all possible moves/choices • Nqueen? Each column and each row in column • Blob-fill? Each neighbor: fill, and unfill • Board often two-dimensional array/grid • Record move, recurse, undo if not done 11/9/2018 Compsci 201, Fall 2018, Backtracking 23
Backtracking APTs • Often use grid[][] to store state/moves • In Java this is actually an array of arrays • int[][] a = new int[4][4] for example • What is a[0]? What is a[0][0]? • Often move must be explicitly undone • Sometimes just try everything 11/9/2018 Compsci 201, Fall 2018, Backtracking 24
Collaborative APT Solving • https: //www 2. cs. duke. edu/csed/newapt/gridgame. ht ml • Shall we play a game? • Each player plays perfectly • If I go here, will you win? 11/9/2018 Compsci 201, Fall 2018, Backtracking 25
Grid. Game Ideas • Have boolean method win. With. Board(board) • For each legal move • Place on board – board now changed • Call win. With. Board(board) -- if true? I lose • Undo move --- take off board and continue • If you could see ahead, you'd know if the move was good. win. With. Board is an oracle 11/9/2018 Compsci 201, Fall 2018, Backtracking 26
What can we do with a board? • Can you determine if [r][c] is legal? • [1][0] is legal, why? • [3][1] is NOT legal, why? ". X. X" ". . X. " ". X. . " ". . " • Suppose there are no legal moves? Answer: Zero/0 • Suppose I place an 'X' and then ask • How many ways to win does opponent have? • If answer is Zero/0, what does placing 'X' do? • This leads to backtracking, believe the code!!! 11/9/2018 Compsci 201, Fall 2018, Backtracking 27
Grid. Game backtracking, count wins private int count. Winners(char[][] board) { int wins = 0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ if (can. Move(board, r, c)){ board[r][c] = 'X'; int opponent. Wins = count. Winners(board); if (opponent. Wins == 0){ wins += 1; } board[r][c] = '. '; } } ". X. X" } "X. X. " ". . X. " return wins; ". X. X" } ". X. . " ". . . . " 11/9/2018 ". . " Compsci 201, Fall 2018, Backtracking 28
Red to try each open space and … ". X. X" ". . X. " ". X. X" "X. X. " ". X. X" ". . X. " ". X. . " ". . . X" ". X. X" "X. X. " ". X. X" "X. . . " Red loses Red wins! Not all moves shown, but result is correct, symmetry! 11/9/2018 Compsci 201, Fall 2018, Backtracking 29
Grid. Game Backtracking • Create grid/board, create legal move method • Return win. Count(original board) 11/9/2018 Compsci 201, Fall 2018, Backtracking 30
Collaborative APT Solving • http: //www. cs. duke. edu/csed/newapt/ratroute. html • Take a step toward the cheese • If that works? Add +1 to total • If that doesn't work? Try another stop • Grid representing "arena" • Methods? • Think verbs 11/9/2018 Compsci 201, Fall 2018, Backtracking 31
Transform input to grid ["X. . X. X. ", "XX. C. X. ", ". . X. X. . ", ". . . . ", "R. XX. . . " ] • Input: String[], transform to char[][] • [0][0] is upper left, 0 th row/column X. X. • Start at rat and. . . • Try each step closer to cheese 11/9/2018 Compsci 201, Fall 2018, Backtracking XX. C. X. X. . R. XX. . . 32
Transform, Initialize, Solve • State and behavior 11/9/2018 Compsci 201, Fall 2018, Backtracking 33
Base cases for cheese-finding • Off the grid? No paths to cheese • On an 'X'? No paths to cheese • On the cheese? One path to cheese 11/9/2018 Compsci 201, Fall 2018, Backtracking 34
Try every possible step that … • Closer to the cheese only, see line 50 • What do we return? Recursive help 11/9/2018 Compsci 201, Fall 2018, Backtracking 35
WOTO http: //bit. ly/201 fall 18 -nov 9 -2 11/9/2018 Compsci 201, Fall 2018, Backtracking 36
Don't Know Much about History • Usenet, Chess, Checkers, … • Alan Biermann, Tom Truscott: Internet Pioneer 11/9/2018 Compsci 201, Fall 2018, Backtracking 37
- Slides: 37