360 likes | 418 Views
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
E N D
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 • Must return to a previous state to pick another path if a dead end is reached
Solving a Maze S G
Move to Right S G
Move Down S G
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
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
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
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)
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
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")
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
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)
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
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
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
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
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
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
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)
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)
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)
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
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)
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
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
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)
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.
K 1 8 2 7 3 6 4 5 The Knight’s Tour Problem • 8 possible first moves, etc.
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
For Friday Queues