Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 1002 Fundamentals of Software Development 2 Chapter 9 – Recursion

Similar presentations


Presentation on theme: "CSE 1002 Fundamentals of Software Development 2 Chapter 9 – Recursion"— Presentation transcript:

1 CSE 1002 Fundamentals of Software Development 2 Chapter 9 – Recursion
Philip Bernhard, PhD Spring 2018

2 Recursion Recursion is a math and programming tool
Technically, not necessary Wasn’t available in early programming languages Advantages of recursion Some things are very easy to do with it, but difficult to do without it Frequently results in very short programs/algorithms Disadvantages of recursion Somewhat difficult to understand at first Sometimes less efficient than non-recursive counterparts (Dr. Stansifer objects!) Presents new opportunities for errors and misunderstanding Tempting to use, even when not necessary Recommendation – use with caution, and only if helpful.

3 Mathematical Recursive Specifications
Recursive Factorial Definition: 1 if N=1 Basis Case N * (N-1)! if N>=2 Recursive Case Recursive Factorial Program: int fact (int n) { if (n==1) return 1; Basis Case else { int x; Recursive Case x = fact (n-1); return x*n; } N! =

4 Simplified Recursive Factorial
int fact (int n) { if (n==1) return 1; else return n*fact(n-1); }

5 One More Example - Fibonacci
Recursive Fibonacci Definition: 0 if N=1 Basis Case 1 if N=2 Basis Case fib(N-1) + fib(N-2) if N>=3 Recursive Case Recursive Fibonacci Program: int fib (int n) { if (n==1) return 0; Basis Case else if (n==2) return 1; Basis Case else { int x,y; Recursive Case x = fib (n-1); y = fib (n-2); return x+y; } fib(n) =

6 Simplified Recursive Fibonacci
int fib (int n) { if (n==1) return 0; else if (n==2) return 1; else return fib(n-1)+fib(n-2); }

7 Looking at Problems Recursively
Looking at a problem recursively, however, can be more difficult. For example, how would you print out the contents of an array recursively? How would you add up the contents of an array recursively? Ok, but these are still easy…

8 Printing the Contents of an Array
void rec_output(int pos, int *vec, int len) { if (pos>=len) return; else { printf("%d ",vec[pos]); rec_output(pos+1,vec,len); } int main(int argc, char *argv[]) { int i; int vector[10]; for (i=0; i<10; i++) vector[i] = 2*i; rec_output(0,vector,10); printf("\n");

9 Simplified Array Print
void rec_output(int pos, int *vec, int len) { if (pos<len){ printf("%d ",vec[pos]); rec_output(pos+1,vec,len); }

10 The Towers of Hanoi Problem
A B C Goal: Move all disks from peg A to peg C, using peg B as an “auxiliary” Rules: Move one disk at a time Never place a disk on top of a smaller disk

11 The Towers of Hanoi Problem Solution for 3 Disks
A non-recursive solution to the problem is not at all obvious.

12 The Towers of Hanoi Problem Viewed Recursively

13 Recursive Hanoi - Trivial
// Move n disks from peg1 to peg2 using peg3 as an auxiliary disk void hanoi(int n, char peg1, char peg2, char peg3) { if (n<1) return; else { hanoi(n-1,peg1,peg3,peg2); printf("Moving Disk From Peg %c to Peg %c\n",peg1,peg2); hanoi(n-1,peg3,peg2,peg1); } int main(int argc, char *argv[]) { int n; printf("Enter n:"); scanf("%d",&n); printf("Value Entered: %d\n",n); hanoi(n,'A','C','B');

14 Simplified Recursive Hanoi
void hanoi(int n, char peg1, char peg2, char peg3) { if (n>=1) { hanoi(n-1,peg1,peg3,peg2); printf("Moving Disk From Peg %c to Peg %c\n",peg1,peg2); hanoi(n-1,peg3,peg2,peg1); } int main(int argc, char *argv[]) { int n; printf("Enter n:"); scanf("%d",&n); /* Error checking should be added */ printf("Value Entered: %d\n",n); hanoi(n,'A','C','B');

15 Recursion and Backtracking
Consider a chess board with a queen, a knight, and some number of pawns. Queen does not move Pawns do not move Knight can move, but cannot land on a pawn Does there exist a sequence of moves that will allow the knight to get to the queen?

16 Initial Configuration
P X X P P X Q P P X P P P P P P P K P

17 A Configuration With No Path
Q P P P P P P P P P P P P K P

18 Recursive Solution How can we look at this problem recursively? P K Q
How would you do it, manually? At any point, the knight has at most 8 options. Select one and continue searching from that point. If this first move does not work, backtrack to the original position, and try another one of the 8 options. X X X X X X X X

19 Input File P – Pawn Q – Queen K – Knight S - Empty SPKSSSSS PSSSSPSS SSSQSSSP SPSSSSSS SPSPSPSP PSSSPSSS SSPSSPSS PPSSPPSS

20 main int main(int argc, char *argv[]) { /* Much abbreviated!!! */ FILE *file_ptr = NULL; const int ROWS = 8; const int COLS = 8; char board[ROWS][COLS]; int row,col; char ch; file_ptr = fopen(argv[1], "r"); if(file_ptr != NULL) { for(row = 0; row < ROWS; row++) { /* Input the board. */ for(col = 0; col < COLS; col++) { board[row][col] = fgetc(file_ptr); } fclose(file_ptr); if (find_path(0,2,ROWS,COLS,board)) /* See if a path exists. */ printf("\nPath Found\n"); /* Position of the knight should be */ else /* deduced from the input file */ printf("\nNo Path Exists\n"); else { printf("\n*** Error opening file\n”); return 0;

21 find_path (Preliminary Version)
/* Knight is trying to move into position at row x, column y max_x and max_y are the number of rows and columns, respectively (8) board is a 2D array containing the chess board */ int find_path(int x, int y, int max_x, int max_y, char board[max_x][max_y]) { if ((x<0) || (y<0) || (x>=max_x) || (y>=max_y)) return 0; else if (board[x][y] == 'P') else if (board[x][y] == 'X') else if (board[x][y] == 'Q') { return 1; } else { /* Next page */

22 find_path (Preliminary Version)
/* Previous page */ else { int success; board[x][y] = 'X'; if (find_path(x-1,y+2,max_x,max_y,board)) success = 1; else if (find_path(x-1,y-2,max_x,max_y,board)) else if (find_path(x+1,y+2,max_x,max_y,board)) else if (find_path(x+1,y-2,max_x,max_y,board)) else if (find_path(x-2,y+1,max_x,max_y,board)) else if (find_path(x-2,y-1,max_x,max_y,board)) else if (find_path(x+2,y+1,max_x,max_y,board)) else if (find_path(x+2,y-1,max_x,max_y,board)) success = 0; board[x][y] = 'S'; } return success;

23 find_path (Second Version)
int find_path(int x, int y, int rows, int cols, char board[rows][cols]) { if (board[x][y] == 'Q') { printf("%d %d\n",x,y); return 1; } else if ((x<0) || (y<0) || (x>rows-1) || (y>cols-1) || (board[x][y] == 'P') || (board[x][y] == 'X')) { return 0; else { board[x][y] = 'X'; if (find_path(x-1,y+2,rows,cols,board) || /* This version also prints out the path */ find_path(x-1,y-2,rows,cols,board) || /* if it exists. Although, it does print */ find_path(x+1,y+2,rows,cols,board) || /* it out in reverse order. Question – how */ find_path(x+1,y-2,rows,cols,board) || /* could that be changed? */ find_path(x-2,y+1,rows,cols,board) || find_path(x-2,y-1,rows,cols,board) || find_path(x+2,y+1,rows,cols,board) || find_path(x+2,y-1,rows,cols,board)) { board[x][y] = 'S';


Download ppt "CSE 1002 Fundamentals of Software Development 2 Chapter 9 – Recursion"

Similar presentations


Ads by Google