More on Recursion - PowerPoint PPT Presentation

1 / 13
About This Presentation
Title:

More on Recursion

Description:

More on Recursion – PowerPoint PPT presentation

Number of Views:60
Avg rating:3.0/5.0
Slides: 14
Provided by: facwebIit
Category:
Tags: more | recursion | tower

less

Transcript and Presenter's Notes

Title: More on Recursion


1
More on Recursion
2
A recursive max function
Int larger (int x, int y) if ( x gt y )
return x return y int max ( int
a, int n) if (n 1) return a0
return larger ( a0, max ( a1, n-1))
main() int a100, n ..
greatest max ( a, n) ..
3
Relook at the Fibonacci solution fib(n) 1 if
n 0 or 1 fib(n 2) fib(n
1) otherwise
int fib (int n) if (n0 n1) return
1 return fib(n-2) fib(n-1)
fib (5)
fib (3)
fib (4)
fib (2)
fib (1)
fib (2)
fib (3)
fib (1)
fib (2)
fib (0)
fib (1)
fib (1)
fib (0)
This is not efficient !! Same sub-problem solved
many times.
fib (1)
fib (0)
4
Tower of Hanoi
A
B
C
5
Tower of Hanoi
A
B
C
6
Tower of Hanoi
A
B
C
7
Tower of Hanoi
A
B
C
8
Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
. .
.
9
Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
. .
10
Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
printf (Disk d c ? c\n, n, from, to)
.
11
Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
printf (Disk d c ? c\n, n, from, to)
towers (n-1, aux, to, from)
12
TOH runs
void towers(int n, char from, char to, char
aux) if (n1) printf ("Disk 1 c -gt
c \n", from, to) return towers
(n-1, from, aux, to) printf ("Disk d c
-gt c\n", n, from, to) towers (n-1, aux, to,
from) main() int n scanf("d", n)
towers(n,'A',C',B')
scd ./a.out 2 Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C scd ./a.out 3 Disk 1 A -gt
C Disk 2 A -gt B Disk 1 C -gt B Disk 3 A -gt
C Disk 1 B -gt A Disk 2 B -gt C Disk 1 A -gt C
13
More TOH runs
scd ./a.out 4 Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C Disk 3 A -gt B Disk 1 C -gt
A Disk 2 C -gt B Disk 1 A -gt B Disk 4 A -gt
C Disk 1 B -gt C Disk 2 B -gt A Disk 1 C -gt
A Disk 3 B -gt C Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C
void towers(int n, char from, char to, char
aux) if (n1) printf ("Disk 1 c -gt
c \n", from, to) return towers
(n-1, from, aux, to) printf ("Disk d c
-gt c\n", n, from, to) towers (n-1, aux, to,
from) main() int n scanf("d", n)
towers(n,'A',C',B')
Write a Comment
User Comments (0)
About PowerShow.com