Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals of Programming II Backtracking with Stacks

Similar presentations


Presentation on theme: "Fundamentals of Programming II Backtracking with Stacks"— Presentation transcript:

1 Fundamentals of Programming II Backtracking with Stacks
Computer Science 112 Fundamentals of Programming II Backtracking with Stacks

2 Backtracking Algorithms
View a 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)
G

9 Backtrack to Previous State
G

10 Continue to the Goal S G

11 Maze is a 2-d grid of characters in a text file
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 columns 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
from linkedstack import LinkedStack def main(): maze = getMazeFromFile() print(maze) (startRow, startCol) = findStartPos(maze) success = getOut(startRow, startCol, maze) if success: print("Maze solved:") else: print("No path out of this maze")

17 Getting the Maze from the File
def getMazeFromFile(): """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 in range(rows): line = fileObj.readline().strip() column = 0 for ch in line: maze[row][column] = ch column += 1 return maze

18 Finding the Start Position
def findStartPos(maze): """Returns the position of the start symbol in the grid.""" for row in range(maze.getHeight()): for column in range(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 return false

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 One Possible Solution 1 2 3 4 5 6 7 8 Q Q Q Q Q Q Q Q

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

24 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 Q Q

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

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

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

28 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 Q x Q x Q x Q x Q x x x x

29 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 Q Q Q (8,5) Q Q

30 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 Q x Q x Q x x Q x x x Q x

31 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 Q Q Q Q Q

32 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 Q Q (7,4) Q Q

33 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

34 For Friday Queues Chapter 8


Download ppt "Fundamentals of Programming II Backtracking with Stacks"

Similar presentations


Ads by Google