Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Copyright (c) Pearson All rights reserved.

Similar presentations


Presentation on theme: "Recursion Copyright (c) Pearson All rights reserved."— Presentation transcript:

1 Recursion Copyright (c) Pearson 2013. All rights reserved.
Recursion Review Recursion Copyright (c) Pearson All rights reserved.

2

3 Recursion recursion: The definition of an operation in terms of itself. Solving a problem using recursion depends on solving smaller occurrences of the same problem. recursive programming: Writing methods that call themselves to solve problems recursively. An equally powerful substitute for iteration (loops) Particularly well-suited to solving certain types of problems

4 Why learn recursion? "cultural experience" - A different way of thinking of problems Can solve some kinds of problems better than iteration Leads to elegant, simplistic, short code (when used well) Many programming languages ("functional" languages such as Scheme, ML, and Haskell) use recursion exclusively (no loops)

5 Recursion and cases Every recursive algorithm involves at least 2 cases: base case: A simple occurrence that can be answered directly. recursive case: A more complex occurrence of the problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem. Some recursive algorithms have more than one base or recursive case, but all have at least one of each. A crucial part of recursive programming is identifying these cases.

6 !Recursion Recursion is not really calling the same function
The arguments are different, so the stack frame is different. As far as the computer goes, they are different functions that are being called.

7 3 essentials for recursion solutions
Way to make the problem data smaller and smaller, so that it approaches some easily solvable value. Way to solve the base case, the smallest data input problem. An assumption, or leap of faith, that we have a method of solving a smaller version of the problem, and a call to that function within our function. The recursive case

8 Fibonacci Sequence The Fibonacci numbers were originally intended to model the growth of a rabbit colony. The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The Fibonacci sequence is defined as follows: fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2), n > 1 Note: The sequence originally started with 1,1,… but in computing we start at 0.

9 Recursive Fibonacci public int fibonacci(int n) { if(n == 0) return 0; else if(n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2); }

10 This is a terribly inefficient
Recomputes all the preceding partial answers Can easily be computed iteratively

11 Recursive Backtracking

12 Backtracking backtracking: A general algorithm for finding solution(s) to a computational problem by trying partial solutions and then abandoning them ("backtracking") if they are not suitable. a "brute force" algorithmic technique (tries all paths; not clever) often (but not always) implemented recursively Applications: producing all permutations of a set of values parsing languages games: anagrams, crosswords, word jumbles, 8 queens combinatorics and logic programming

13 Backtracking algorithms
A general pseudo-code algorithm for backtracking problems: explore(choices): if there are no more choices to make: stop. else: Make a single choice C from the set of choices. Remove C from the set of choices. explore the remaining choices. Un-make choice C. Backtrack!

14 Backtracking strategies
When solving a backtracking problem, ask these questions: What are the "choices" in this problem? What is the "base case"? (How do I know when I'm out of choices?) How do I "make" a choice? Do I need to create additional variables to remember my choices? Do I need to modify the values of existing variables? How do I explore the rest of the choices? Do I need to remove the made choice from the list of choices? Once I'm done exploring the rest, what should I do? How do I "un-make" a choice?

15 The N-Queens Problem Suppose you have 8 chess queens...
...and a chess board We'll start with a description of a problem which involves a bunch of queens from a chess game, and a chess board.

16 The N-Queens Problem Can the queens be placed on the board so that no two queens are attacking each other ? Some of you may have seen this problem before. The goal is to place all the queens on the board so that none of the queens are attacking each other.

17 The N-Queens Problem Two queens are not allowed in the same row...
If you play chess, then you know that this forbids two queens from being in the same row...

18 The N-Queens Problem Two queens are not allowed in the same row, or in the same column... ...or in the same column...

19 The N-Queens Problem Two queens are not allowed in the same row, or in the same column, or along the same diagonal. ...or along the same diagonal. As a quick survey, how many of you think that a solution will be possible? In any case, we shall find out, because we will write a program to try to find a solution. As an aside, if the program does discover a solution, we can easily check that the solution is correct. But suppose the program tells us that there is no solution. In that case, there are actually two possibilies to keep in mind: 1. Maybe the problem has no solution. 2. Maybe the problem does have a solution, and the program has a bug! Moral of the story: Always create an independent test to increase the confidence in the correctness of your programs.

20 The N-Queens Problem N Queens
The number of queens, and the size of the board can vary. N columns The program that we write will actually permit a varying number of queens. The number of queens must always equal the size of the chess board. For example, if I have six queens, then the board will be a six by six chess board. N rows

21 The N-Queens Problem We will write a program which tries to find a way to place N queens on an N x N chess board. At this point, I can give you a demonstration of the program at work. The demonstration uses graphics to display the progress of the program as it searches for a solution. During the demonstration, a student can provide the value of N. With N less than 4, the program is rather boring. But N=4 provides some interest. N=10 takes a few minutes, but it is interesting to watch and the students can try to figure out the algorithm used by the program.

22 How the program works The program uses a stack to keep track of where each queen is placed. I want to show you the algorithm that the program uses. The technique is called backtracking. The key feature is that a stack is used to keep track of each placement of a queen.

23 How the program works Each time the program decides to place a queen on the board, the position of the new queen is stored in a record which is placed in the stack. For example, when we place the first queen in the first column of the first row, we record this placement by pushing a record onto the stack. This record contains both the row and column number of the newly- placed queen. ROW 1, COL 1

24 How the program works We also have an integer variable to keep track of how many rows have been filled so far. In addition to the stack, we also keep track of one other item: an integer which tells us how many rows currently have a queen placed. ROW 1, COL 1 1 filled

25 How the program works Each time we try to place a new queen in the next row, we start by placing the queen in the first column... ROW 2, COL 1 When we successfully place a queen in one row, we move to the next row. We always start by trying to place the queen in the first column of the new row. ROW 1, COL 1 1 filled

26 How the program works ...if there is a conflict with another queen, then we shift the new queen to the next column. ROW 2, COL 2 But each new placement must be checked for potential conflicts with the previous queen. If there is a conflict, then the newly-placed queen is shifted rightward. ROW 1, COL 1 1 filled

27 How the program works If another conflict occurs, the queen is shifted rightward again. ROW 2, COL 3 Sometimes another conflict will occur, and the newly-placed queen must continue shifting rightward. ROW 1, COL 1 1 filled

28 How the program works When there are no conflicts, we stop and add one to the value of filled. ROW 2, COL 3 When the new queen reaches a spot with no conflicts, then the algorithm can move on. In order to move on, we add one to the value of filled... ROW 1, COL 1 2 filled

29 How the program works Let's look at the third row. The first position we try has a conflict... ROW 3, COL 1 ROW 2, COL 3 ...and place a new queen in the first column of the next row. ROW 1, COL 1 2 filled

30 How the program works ...so we shift to column 2. But another conflict arises... ROW 3, COL 2 ROW 2, COL 3 In this example, there is a conflict with the placement of the new queen, so we move her rightward to the second column. ROW 1, COL 1 2 filled

31 How the program works ...and we shift to the third column.
Yet another conflict arises... ROW 3, COL 3 ROW 2, COL 3 Another conflict arises, so we move rightward to the third column. ROW 1, COL 1 2 filled

32 How the program works ...and we shift to column 4. There's still a conflict in column 4, so we try to shift rightward again... ROW 3, COL 4 ROW 2, COL 3 Yet another conflict arises, so we move to the fourth column. The key idea is that each time we try a particular location for the new queen, we need to check whether the new location causes conflicts with our previous queens. If so, then we move the new queen to the next possible location. ROW 1, COL 1 2 filled

33 How the program works ...but there's nowhere else to go. 2 filled
ROW 3, COL 4 ROW 2, COL 3 Sometimes we run out of possible locations for the new queens. This is where backtracking comes into play. ROW 1, COL 1 2 filled

34 How the program works When we run out of room in a row: pop the stack,
reduce filled by 1 and continue working on the previous row. ROW 2, COL 3 To backtrack, we throw out the new queen altogether, popping the stack, reducing filled by 1, and returning to the previous row. At the previous row, we continue shifting the queen rightward. ROW 1, COL 1 1 filled

35 How the program works Now we continue working on row 2, shifting the queen to the right. ROW 2, COL 4 Notice that we continue the previous row from the spot where we left off. The queen shifts from column 3 to column 4. We don't return her back to column 1. It is the use of the stack that lets us easily continue where we left off. The position of this previous queen is recorded in the stack, so we can just move the queen rightward one more position. ROW 1, COL 1 1 filled

36 How the program works This position has no conflicts, so we can increase filled by 1, and move to row 3. ROW 2, COL 4 The new position for row 2 has no conflicts, so we can increase filled by 1, and move again to row 3. ROW 1, COL 1 2 filled

37 How the program works In row 3, we start again at the first column. 2
ROW 3, COL 1 ROW 2, COL 4 At the new row, we again start at the first column. So the general rules are: When the algorithm moves forward, it always starts with the first column. But when the algorithm backtracks, it continues whereever it left off. ROW 1, COL 1 2 filled

38 Exercise Suppose we have a Board class with the following methods:
Write a method solveQueens that accepts a Board as a parameter and tries to place 8 queens on it safely. Your method should stop exploring if it finds a solution. Method/Constructor Description public Board(int size) construct empty board public boolean isSafe(int row, int column) true if queen can be safely placed here public void place(int row, int column) place queen here public void remove(int row, int column) remove queen from here public String toString() text display of board

39 Recursive Solution // Recursively searches for a solution to 8 queens on this // board, starting with the given column, returning true if a // solution is found and storing that solution in the board. // PRE: queens have been safely placed in columns 1 to (col-1) public static boolean explore(Board board, int col) { if (col > board.size()) { return true; // base case: all columns are placed } else { // recursive case: place a queen in this column for (int row = 1; row <= board.size(); row++) { if (board.isSafe(row, col)) { board.place(row, col); // choose if (explore(board, col + 1)) { // explore return true; // solution found } b.remove(row, col); // un-choose return false; // no solution found


Download ppt "Recursion Copyright (c) Pearson All rights reserved."

Similar presentations


Ads by Google