Upload
rosamond-foster
View
229
Download
0
Embed Size (px)
Citation preview
RecursionRecursion
When to use it and when not to When to use it and when not to use ituse it
Basics of RecursionBasics of Recursion
Recursion uses a methodRecursion uses a method Within that method a call is made Within that method a call is made
to the same methodto the same method Somewhere within the method, Somewhere within the method,
the loop must be exitedthe loop must be exited
DisadvantagesDisadvantages
3 major disadvantages3 major disadvantages Slow algorithmsSlow algorithms e.g. recursive Fibonacci:e.g. recursive Fibonacci:
int fib (int n)int fib (int n)
{{
if (n <= 2) return 1;if (n <= 2) return 1;
else return fib (n – 1) + fib (n – 2); else return fib (n – 1) + fib (n – 2);
}}
Disadvantages Cont.Disadvantages Cont.
Procedure call overheads: 30% Procedure call overheads: 30% slowerslower
Not much time lost thoughNot much time lost though
Data on stack (stack overflow)Data on stack (stack overflow) Not much of a problem these daysNot much of a problem these days Watch out for using more than the Watch out for using more than the
limitlimit
Disadvantages Disadvantages SummarySummary The first one is the one to watch The first one is the one to watch
out for (slower algorithms)out for (slower algorithms) The other two can almost be The other two can almost be
ignored (procedure call overheads ignored (procedure call overheads and data on stack)and data on stack)
What to Use InsteadWhat to Use Instead
If iteration is easy to program, If iteration is easy to program, use ituse it
If dynamic programming works, If dynamic programming works, use it insteaduse it instead
Why Use Recursion?Why Use Recursion?
Easy to programEasy to program Easy to debugEasy to debug Shorter than dynamic Shorter than dynamic
programmingprogramming
n Queens Problemn Queens Problem
Place n queens on an n x n chess Place n queens on an n x n chess board so that no queen is board so that no queen is attacked by another queenattacked by another queen
Find out the total number of Find out the total number of configurationsconfigurations
n Queens Solutionn Queens Solution
The most obvious solution is to The most obvious solution is to recursively add queens, trying all recursively add queens, trying all possible placementspossible placements
It is easy to see that there can It is easy to see that there can only be one queen per columnonly be one queen per column
At each step, you know the At each step, you know the position of the queens for the first position of the queens for the first i columnsi columns
n Queens Solution n Queens Solution Cont.Cont. You try to place a queen in the i + You try to place a queen in the i +
1 column1 column If successful, you move on to the If successful, you move on to the
next step, trying to place a queen next step, trying to place a queen in the i + 2 columnin the i + 2 column
n Queens Solution n Queens Solution Cont.Cont.QQ QQ XX QQ XX QQ XX
XX
XX
XX
QQ QQ XX XX
XX QQ
QQ XX QQ XX QQ XX QQ XX
QQ XX
XX
XX
XX XX XX
QQ QQ XX QQ XX XX
n Queens Solution n Queens Solution Cont.Cont.
XX QQ QQ XX XX
QQ XX
QQ XX
QQ XX
XX QQ XX XX
QQ QQ QQ XX QQ XX
XX XX QQ QQ XX
QQ XX
XX
XX
XX QQ QQ QQ XX
XX QQ
n Queens Solution n Queens Solution Cont.Cont.
QQ QQ XX QQ XX XX
XX
XX
XX
QQ QQ XX QQ XX QQ XX
QQ QQ XX XX XX
XX QQ QQ XX QQ XX
XX
XX
XX
XX QQ QQ XX
QQ QQ QQ QQ XX
n Queens Solution n Queens Solution Cont.Cont.
QQ XX XX XX XX
FINIS
HED
FINIS
HED
XX
QQ XX
XX
XX XX XX
QQ XX QQ QQ XX QQ XX
n Queens Solution n Queens Solution Cont.Cont. void search (int col)void search (int col)
{{ if (col == n)if (col == n) {{ count++;count++; return;return; }} for (int row = 0; row < n; row++)for (int row = 0; row < n; row++) if (not_attacked (row, col))if (not_attacked (row, col)) {{ board [col] = row;board [col] = row; search (col + 1);search (col + 1); }}}}
n Queens Solution n Queens Solution Cont.Cont. The The not_attackednot_attacked method simply method simply
checks to see if the queen can be checks to see if the queen can be placed in that particular blockplaced in that particular block
n Queens Analysisn Queens Analysis
Since the number of possibilities is Since the number of possibilities is small, recursion is quick enough in this small, recursion is quick enough in this casecase
For a 10 x 10 board it runs for 0.11 sFor a 10 x 10 board it runs for 0.11 s This solution is also an example of This solution is also an example of
depth first searchdepth first search In questions similar to this, use In questions similar to this, use
recursion, since it is easier to programrecursion, since it is easier to program
Little Flower Shop IOI Little Flower Shop IOI ’99’99 You want to arrange the window of your flower shop in You want to arrange the window of your flower shop in
a most pleasant way. You have F bunches of flowers, a most pleasant way. You have F bunches of flowers, each being of a different kind and at least as many each being of a different kind and at least as many vases (V) ordered in a row.vases (V) ordered in a row.
The bunches are moveable and are uniquely identified The bunches are moveable and are uniquely identified by integers between 1 and F. These id-numbers have by integers between 1 and F. These id-numbers have a significance. They determine the required order of a significance. They determine the required order of appearance of the flower bunches in the row of vases. appearance of the flower bunches in the row of vases. The bunch i must be on the left of bunch j whenever i The bunch i must be on the left of bunch j whenever i < j.< j.
Excess vases will be left empty. A vase can only hold Excess vases will be left empty. A vase can only hold one bunch of flowers.one bunch of flowers.
Little Flower Shop Little Flower Shop Cont.Cont. Each vase has a distinct characteristic (just like Each vase has a distinct characteristic (just like
flowers do). Hence, putting a bunch of flowers in a flowers do). Hence, putting a bunch of flowers in a vase results in a certain aesthetic value. These values vase results in a certain aesthetic value. These values are presented in the following table:are presented in the following table:
VASESVASES
11 22 33 44 55
FLOW
ER
FLOW
ER
SS
11 77 2323 -5-5 2424 1616
22 55 2121 -4-4 1010 2323
33 -21-21 55 -4-4 -20-20 2020
Flower Solution 1Flower Solution 1
We could use recursion:We could use recursion: int flo (int f, int v)int flo (int f, int v)
{{
if (f == F)if (f == F)
return 0;return 0;
int m = 0;int m = 0;
for (; v <= V – F + f ; v++)for (; v <= V – F + f ; v++)
m = max (m, grid [f][v] + m = max (m, grid [f][v] +
flo (f + 1, v));flo (f + 1, v));
return m;return m;
}}
Flower Solution 1 Flower Solution 1 AnalysisAnalysis In the initial problem, the vase In the initial problem, the vase
numbers must also be outputnumbers must also be output It is far too slowIt is far too slow It tries every solution to find the It tries every solution to find the
maximummaximum
Flower Solution 2Flower Solution 2
The first solution was too slowThe first solution was too slow This time we’ll try dynamic This time we’ll try dynamic
programmingprogramming Start from the second-last rowStart from the second-last row Scan each row from left to rightScan each row from left to right Add the maximum value in each Add the maximum value in each
blockblock
Flower Solution 2 Flower Solution 2 Cont.Cont. int m;int m;for (int i = F - 2; i >= 0; i--)for (int i = F - 2; i >= 0; i--){{ m = -100;m = -100; for (int j = V – F + i; j >= i;j--)for (int j = V – F + i; j >= i;j--) {{ m = max (m, grid [i + 1][j + 1]);m = max (m, grid [i + 1][j + 1]); grid [i][j] += m;grid [i][j] += m; }}
Flower Solution 2 Flower Solution 2 Cont.Cont. int answer = -1000000;int answer = -1000000;
for (int i = 0; i < F; i++)for (int i = 0; i < F; i++)
ans = max (ans, grid [0][i]);ans = max (ans, grid [0][i]);
Flower Solution 2 Flower Solution 2 Cont.Cont. The solution is The solution is
illustrated in the illustrated in the tables on the righttables on the right
The top table is The top table is beforebefore
The bottom table The bottom table is afteris after
Yellow numbers Yellow numbers were changedwere changed
11 22 33 44 55
11 77 2323 -5-5 2424 1616
22 55 2121 -4-4 1010 2323
33 --2121
55 -4-4 --2020
2020
11 22 33 44 55
11 4141 5353 2525 2424 1616
22 55 4141 1616 3030 2323
33 --2121
55 -4-4 --2020
2020
Flower Solution 2 Flower Solution 2 AnalysisAnalysis Only the necessary calculations Only the necessary calculations
are doneare done Much faster algorithm (0.05 s, Much faster algorithm (0.05 s,
quicker than 2 s allowed)quicker than 2 s allowed) To determine the vase numbers is To determine the vase numbers is
easyeasy
Flower AnalysisFlower Analysis
In this case, recursion is not fast In this case, recursion is not fast enoughenough
As always, if dynamic As always, if dynamic programming works, use itprogramming works, use it
Not all problems can be solved Not all problems can be solved with dynamic programming, since with dynamic programming, since it uses more memoryit uses more memory
ConclusionConclusion
When recursion runs within the When recursion runs within the time limit, use ittime limit, use it
If it doesn’t, try using dynamic If it doesn’t, try using dynamic programming or another programming or another techniquetechnique
If you can’t do it any other way, If you can’t do it any other way, use recursion to get partial marksuse recursion to get partial marks
Conclusion Cont.Conclusion Cont.
Remember, many other Remember, many other techniques use recursion, so it is techniques use recursion, so it is important to know wellimportant to know well
Most graph theory (shortest Most graph theory (shortest paths, etc.) uses recursionpaths, etc.) uses recursion