1 / 36

Computer Science 112

Computer Science 112. Fundamentals of Programming II Backtracking. Backtracking Algorithms. View the problem as a space of states; advance from a start state in search of a goal state Can choose different paths through the state space

Download Presentation

Computer Science 112

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. Computer Science 112 Fundamentals of Programming II Backtracking

  2. Backtracking Algorithms • View the problem as a space of states; advance from a start state in search of a goal state • Can choose different paths through the state space • Must return to a previous state to pick another path if a dead end is reached

  3. Solving a Maze S G

  4. Move to Right S G

  5. Move Down S G

  6. Move to Right (Choice Point) S G

  7. Move Down (Choice Point) S G

  8. Reach a Dead End (Must Backtrack) S G

  9. Backtrack to Previous State S G

  10. Continue to the Goal S G

  11. 23 50 ************************************************** ******* ******** **** ******* ************** ************* ******** **** ******* ************** *** * *** **** P ************** ** ****** * *** **** **** ******* *** ** * ******* **** **** ******* *** ******* ** * ******************* **** ******* *** ******* ** ******************* **** ******* *** ******* ************************* **** ******* *** ** ********* **** *** *** ** **** **** ******************** **** *** ********** **** **** ****** **** *** ********** **** ************************* **** *** ********** **** ************************* **** *** **** ************ ************ **** ******** ********** ************ ************ **** ******** ********** ************ ******* **** ******** ***** ************ **** ******* **** ******************* **** ******* **** ************************************* ******* **** ************************************* ************ ************************************* T ************************************************** Maze is a 2-d grid of characters in a text file Rows and columns appear on the first line P is start state, T is goal state

  12. 23 50 ************************************************** ******* ******** **** ******* ************** ************* ******** **** ******* ************** *** * *** **** P.......************** ** ****** * *** **** **** *******.*** ** * ******* **** **** *******.*** ******* ** * ******************* **** *******.*** ******* ** ******************* **** *******.*** ******* ************************* **** *******.*** ** ********* **** ***.....*** ** **** **** ******************** **** ***.********** **** **** ****** **** ***.********** **** ************************* **** ***.********* **** ************************* **** ***...... **** ************ ************ **** ******** ********** ************ ************ **** ******** ********** ************ ******* **** ******** ***** ************ **** ******* **** ******************* **** ******* **** ************************************* ******* **** ************************************* ************ ************************************* T ************************************************** Like Hansel, leave a trail of markers (dots) as you move forward on a path When you hit a dead end, follow the trail back to the most recent choice point and take another path

  13. Data for a Maze Solver • A two-dimensional grid of strings • Initially, grid cells contain either • ' ' (an empty spot on a path) • '*' (a wall) • 'P' (the start state - a parking lot) • 'T' (the end state or goal - a mountain top) • Will write '.' to a cell to indicate that it was visited already

  14. Minimal Set of Grid Operations g = Grid(height, width, fillValue = None) g.getHeight() Returns the number of rows g.getWidth() Returns the number of rows str(g) Returns a string representation g[row][column] Returns item at (row, column) g[row][column] = item Stores item at (row, colum)

  15. Choice Points • Each choice point consists of a row and a column • Represent a choice point as a tuple (row, column) and save these points on a stack

  16. Data and main Function from grid import Grid fromlinkedstackimportLinkedStack defmain(): maze = getMazeFromFile() print(maze) (startRow, startCol) = findStartPos(maze) success = getOut(startRow, startCol, maze) if success: print("Maze solved:") print(maze) else: print("No path out of this maze")

  17. Getting the Maze from the File defgetMazeFromFile(): """Reads the maze from a text file and returns a grid that represents it.""" name = input("Enter a file name for the maze: ") fileObj = open(name, 'r') firstLine = list(map(int, fileObj.readline().strip().split())) rows = firstLine[0] columns = firstLine[1] maze = Grid(rows, columns, "*") for row inrange(rows): line = fileObj.readline().strip() column = 0 forchin line: maze[row][column] = ch column += 1 return maze

  18. Finding the Start Position deffindStartPos(maze): """Returns the position of the start symbol in the grid.""" for row inrange(maze.getHeight()): for column inrange(maze.getWidth()): if maze[row][column] == 'P': return (row, column) return (-1, -1)

  19. Possible States and Actions • Begin by pushing a choice point for the start cell onto the stack • While the stack is not empty • Pop a choice point • If there is a ‘T’ at that point, return true • Otherwise, • Mark the cell at the current point with ‘.’ • push all of the adjacent points that do not contain ‘*‘ or ‘.’ onto the stack • If the stack is empty return false

  20. Algorithm for getOut Create a new stack Push the choice point for the starting cell onto the stack while the stack is not empty Pop a choice point from the stack if the cell at that point contains 'T' return true else mark the cell at that point with '.' push all of the adjacent points that do not contain '.' or '*' onto the stack returnfalse

  21. The Eight Queens Problem • Position eight queens on a chessboard so that none of them can capture another one • A queen can move any number of positions in any direction

  22. Q Q Q Q Q Q Q Q One Possible Solution 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  23. Q Backtracking Solution • Place first queen in square (1,1) 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  24. Q Q Backtracking Solution • Place second queen in the first position in the second column that is not threatened (2,3) 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  25. Q Q Q Backtracking Solution • Continue this process until eight queens have been placed or a block occurs 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 (5,3)

  26. Q Q Q Q Backtracking Solution • Continue this process until eight queens have been placed or a block occurs 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 (2,4)

  27. Q Q Q Q Q Backtracking Solution • Continue this process until eight queens have been placed or a block occurs 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 (4,5)

  28. Q Q Q Q Q x x x x x x x x Backtracking Solution • We can’t place a queen in column 6, so we back up to column 5 and try another position 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  29. Q Q Q Q Q Backtracking Solution • We can’t place a queen in column 6, so we back up to column 5 and try another position 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 (8,5)

  30. Q Q Q Q Q x x x x x x x x Backtracking Solution • But all squares in column 6 are still under attack, so we must back up to column 5 again 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  31. Q Q Q Q Q Backtracking Solution • There are no options left in column 5, so we back up to column 4 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8

  32. Q Q Q Q Backtracking Solution • There are no options left in column 5, so we back up to column 4, etc. 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 (7,4)

  33. K The Knight’s Tour Problem • Place a knight at any position (x,y) on the board. Return a path such that the knight visits each position exactly once.

  34. K 1 8 2 7 3 6 4 5 The Knight’s Tour Problem • 8 possible first moves, etc.

  35. Backtracking with Stacks • Applications are different, but the pattern of the algorithm is the same • Search a space of states until a goal is found • Back up when a dead end is reached and try another move

  36. For Friday Queues

More Related