Java Lect 24
Java Lect 24
Recursion
29th feb 2005
[email protected]
Recursion
solve(problem)
{
If problem is simple
Return the answer
Else
{
Break the problem as p1,p2,p3 pn
For each problem P
solve (P);
}
}
Saturday, January
16, 2016
CFILT
java
Properties
Calls the same function with smaller i/p.
Divide and conquer strategy
Saturday, January
16, 2016
CFILT
java
Example
Little tricky
Saturday, January
16, 2016
CFILT
java
Application of recursion
?
Saturday, January
16, 2016
CFILT
java
Towers of Hanoi
Lets try this
Hanoi
Rules
Input
Output
Solution for 1, 2, 3, 4, n
Saturday, January
16, 2016
CFILT
java
What is input ?
-Number of discs!
What is output?
-Final state ?
Y/N
-Sequence of moves ?
-How to represent ?
Saturday, January
16, 2016
CFILT
java
When to stop ?
Solution for x discs is very simple. Solve it
directly
Saturday, January
16, 2016
CFILT
java
Steps
Problem definition
Input representation
Output representation
Algorithm
Implementation
Saturday, January
16, 2016
CFILT
java
Design
We know
Recursive condition
Terminating condition
Saturday, January
16, 2016
CFILT
java
Input/Output
Saturday, January
16, 2016
CFILT
java
Skeleton code
Solve_hanoi(integer n, towers t1, t2, t3)
{
Do something.
Do something
Saturday, January
16, 2016
CFILT
java
Temination
Solve_hanoi(integer n, towers t1, t2, t3)
{
If (n == 1) then
move the discn from t1 to t3
Do something
solve_hanoi(some small n)
Do something.
Do something
}
Saturday, January
16, 2016
CFILT
java
Subdivsion
N-1
discs
Nth disc
Start(X)
Saturday, January
16, 2016
Middle(Z)
CFILT
End(Y)
java
Contd.
Solve_hanoi(integer n, towers t1, t2, t3)
{
1. Move the n-1 discs from t1 to t2 using t3
2. Now move only remaining disc from t1 to t3
3. Move the n-1 discs from t2 to t3 using t1
}
Which steps are recursive ?
Saturday, January
16, 2016
CFILT
java
}
Saturday, January
16, 2016
CFILT
java
Saturday, January
16, 2016
CFILT
java
Reference
Play the game or see the solutions here
http://www.mazeworks.com/hanoi/
Recursion:
http://www.cs.ucla.edu/~klinger/dorene/math4.htm
Saturday, January
16, 2016
CFILT
java
Saturday, January
16, 2016
CFILT
java