1 / 37

Compsci 201 Backtracking

Compsci 201 Backtracking. Owen Astrachan ola@cs.duke.edu November 9, 2018. S is for …. Stack Last in, First Out, source of overflow! Software Joys and sorrows, eating the world. Plan for Today. Backtracking: try, retry, try again Paradigm for searching and much more

kress
Télécharger la présentation

Compsci 201 Backtracking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Compsci 201Backtracking Owen Astrachan ola@cs.duke.edu November 9, 2018 Compsci 201, Fall 2018, Backtracking

  2. S is for … • Stack • Last in, First Out, source of overflow! • Software • Joys and sorrows, eating the world Compsci 201, Fall 2018, Backtracking

  3. 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 Compsci 201, Fall 2018, Backtracking

  4. Flood Fill, Blob Count https://github.com/astrachano/backtracking-fall18 Compsci 201, Fall 2018, Backtracking

  5. Applications • Using draw/paint program, fill a region • Redeye removal • Give image partially transparent background • Finding edges or blobs in image processing Compsci 201, Fall 2018, Backtracking

  6. 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, … Compsci 201, Fall 2018, Backtracking

  7. 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 • BlobModel.blobFill method: (row,col) for start • lookFor character, e.g., ‘*’ • fillWith character, e.g., ‘1’ or ‘7’ or … • If blob not big enough? Erase: lookFor = fillWith Compsci 201, Fall 2018, Backtracking

  8. 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 Compsci 201, Fall 2018, Backtracking

  9. Lookfor for Blobs Everywhere • Two parameters in each call to blobFill fillWith lookFor Compsci 201, Fall 2018, Backtracking

  10. Blobs starting at (row,col) • Ask each of four neighbors for their blob-size • Add me, +1, to what they report back Compsci 201, Fall 2018, Backtracking

  11. When does process stop? • If (row,col) is not in bounds? Do nothing • If grid[row][col] != lookFor? 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 Compsci 201, Fall 2018, Backtracking

  12. blobFill(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 • myGrid[row][col] = fillWith • Unless fillWith == lookFor, not infinite! Compsci 201, Fall 2018, Backtracking

  13. WOTO for Blobs http://bit.ly/201fall18-nov9-1 Compsci 201, Fall 2018, Backtracking

  14. 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/ Compsci 201, Fall 2018, Backtracking

  15. 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 … Compsci 201, Fall 2018, Backtracking

  16. Use BFS instead of recursion https://github.com/astrachano/backtracking-fall18 • Details: queue, parallel grid [][], rowDelta • Easier • Similar Compsci 201, Fall 2018, Backtracking

  17. How to search 8 neighbors? • We need to make 8 recursive calls • W, NW, N, NE, E, SE, S, SW • See coding “trick” below int[] rd = {0,-1,-1,-1,0,1,1,1}; int[] cd = {-1,-1,0,1,1,1,0,-1}; for(int d = 0; d < rd.length; d+= 1){ intnr = row + rd[d]; intnc = col + cd[d]; size += blobFill(nr,nc, …) } Compsci 201, Fall 2018, Backtracking

  18. 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 Compsci 201, Fall 2018, Backtracking

  19. Exhaustive Search • Can explore every possible move in tic-tac-toe • 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 Compsci 201, Fall 2018, Backtracking

  20. N-Queens: Know History • Can we place N queens on NxN board so no queen attacks another • 4x4 or 8x8 or … Compsci 201, Fall 2018, Backtracking

  21. 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 Compsci 201, Fall 2018, Backtracking

  22. Code for Nqueens Backtracking • Done when c == N • Place queens, recurse, unplace and try again • Return true • All placed • Recursive • Use myBoard • Track moves Compsci 201, Fall 2018, Backtracking

  23. 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 Compsci 201, Fall 2018, Backtracking

  24. 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 Compsci 201, Fall 2018, Backtracking

  25. Collaborative APT Solving • https://www2.cs.duke.edu/csed/newapt/gridgame.html • Shall we play a game? • Each player plays perfectly • If I go here, will you win? Compsci 201, Fall 2018, Backtracking

  26. GridGame Ideas • Have boolean method winWithBoard(board) • For each legal move • Place on board – board now changed • Call winWithBoard(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. winWithBoard is an oracle Compsci 201, Fall 2018, Backtracking

  27. What can we do with a board? ".X.X" "..X." ".X.." "...." • Can you determine if [r][c] is legal? • [1][0] is legal, why? • [3][1] is NOT legal, why? • 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!!! Compsci 201, Fall 2018, Backtracking

  28. GridGame backtracking, count wins private int countWinners(char[][] board) { int wins = 0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ if (canMove(board,r,c)){ board[r][c] = 'X'; int opponentWins = countWinners(board); if (opponentWins == 0){ wins += 1; } board[r][c] = '.'; } } } return wins; } ".X.X" "X.X." ".X.." "...." ".X.X" "X.X." ".X.X" "...." ".X.X" "..X." ".X.." "...." Compsci 201, Fall 2018, Backtracking

  29. 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." ".X.X" "X..." Red loses ".X.X" "..X." ".X.." "...." ".X.X" "..X." ".X.." "...X" ".X.X" "X.X." ".X.." "...X" Red wins! Not all moves shown, but result is correct, symmetry! Compsci 201, Fall 2018, Backtracking

  30. GridGame Backtracking • Create grid/board, create legal move method • Return winCount(original board) Compsci 201, Fall 2018, Backtracking

  31. 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 Compsci 201, Fall 2018, Backtracking

  32. Transform input to grid ["X..X.X.", "XX.C.X.", ".......", "..X.X..", ".......", "R.XX..." ] • Input: String[], transform to char[][] • [0][0] is upper left, 0th row/column • Start at rat and ... • Try each step closer to cheese X..X.X. XX.C.X. ....... ..X.X.. ....... R.XX... Compsci 201, Fall 2018, Backtracking

  33. Transform, Initialize, Solve • State and behavior Compsci 201, Fall 2018, Backtracking

  34. 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 Compsci 201, Fall 2018, Backtracking

  35. Try every possible step that … • Closer to the cheese only, see line 50 • What do we return? Recursive help Compsci 201, Fall 2018, Backtracking

  36. WOTO http://bit.ly/201fall18-nov9-2 Compsci 201, Fall 2018, Backtracking

  37. Don't Know Much about History • Usenet, Chess, Checkers, … • Alan Biermann, Tom Truscott: Internet Pioneer Compsci 201, Fall 2018, Backtracking

More Related