CSE 1002 Fundamentals of Software Development 2 Chapter 9 – Recursion

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

COSO 1030 Section 4 Recursion. What is about Towers of Hanoi Divide and Conquer Strategy Recursion and Induction Thinking Recursively Recursion Pitfalls.
ITEC200 – Week07 Recursion. 2 Learning Objectives – Week07 Recursion (Ch 07) Students can: Design recursive algorithms to solve.
Chapter 15 Recursive Algorithms.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Lecture 4 1) RECURSION 2)BACKTRACKING 3)LOOK AHEAD.
Recursion Gordon College CPS212
Programming Recursion “To Iterate is Human, to Recurse, Divine” -- L. Peter Deutsch.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Data Structures Using C++ 2E Chapter 6 Recursion.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
1 Storage Classes, Scope, and Recursion Lecture 6.
Recursion Recursion is a math and programming tool –Technically, not necessary Advantages of recursion –Some things are very easy to do with it, but difficult.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Data Structures and Algorithms Stacks. Stacks are a special form of collection with LIFO semantics Two methods int push( Stack s, void *item ); - add.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Recursion. Circular Definition Circular definition Circular definition Dialectic materialism is materialism that is dialectic. Dialectic materialism is.
Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1.
Chapter 8 Recursion Modified.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Recursion Recursive definitions Recursive methods Run-time stack & activation records => Read section 2.3.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursive. Recursive F(n) = F(n-1) + F(n-2) n! = (n-1)! x n C(m,n) = C(m-1,n-1)+C(m-1,n)......
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion.
Recursion Data Structure Submitted By:- Dheeraj Kataria.
Chapter Topics Chapter 16 discusses the following main topics:
Recursion - see Recursion
COMP 51 Week Fourteen Recursion.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Recursion Chapter 12.
Towers of Hanoi Move n (4) disks from pole A to pole C
Chapter 15 Recursion.
2-D arrays a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion Chapter 10.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
1) RECURSION 2) BACKTRACKING 3) LOOK AHEAD
Announcements Final Exam on August 17th Wednesday at 16:00.
Jordi Cortadella Department of Computer Science
Recursion - see Recursion
Recursion Recursion is a math and programming tool
The Power of Calling a Method from Itself
CS201: Data Structures and Discrete Mathematics I
Announcements Final Exam on August 19th Saturday at 16:00.
PPT1: How failures come to be
Stacks & Recursion.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Recursion: The Mirrors
Java Programming: Chapter 9: Recursion Second Edition
Stacks & Recursion.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Exam #1 February 23rd (Next Friday)
Recursion Chapter 12.
ITEC324 Principle of CS III
Recursive Thinking.
Presentation transcript:

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

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.

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! =

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

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) =

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); }

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…

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");

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); }

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

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

The Towers of Hanoi Problem Viewed Recursively

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');

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');

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?

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

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

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

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

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;

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 */

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;

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';