Professional Documents
Culture Documents
Lec2 2
Lec2 2
1) RECURSION
2) BACKTRACKING
3) LOOK AHEAD
waitheart_iba@yahoo.com
Recursion
What is Recursion?
A recursive function is a function that calls itself.
EG: finding the factorial of a number:
non-recursive
Recursive method
long factorial (long n)
long factorial (long number)
fact = 1; {
for (i=1;i<=n;i++) if (number == 1) return 1;
else
fact = fact*i; return(number*factorial(number - 1));
return fact; }
waitheart_iba@yahoo.com main( ) - Next slide
Recursion
waitheart_iba@yahoo.com
Recursion
• EG 2 : Sum of n Natural Numbers:
int sum(n) int sum(n)
{ { int i,sum;
if (n==1) for (i=1;i<=n;i++)
return 1; sum = sum+i;
else return sum;
return( n+ sum(n-1));
}
}
waitheart_iba@yahoo.com
Previous program
• recursive • non_-recursive
• #include<iostream.h>
• #include<iostream.h> • void main()
• int sum(int n) • {int i ,num,sum=0;
• {if(n==1) • cin>>num;
• return 1; • for(i=1;i<=num;i++)
• else return (n*sum(n-1)); • sum+=i;
• } • cout<<sum;
• void main() • }
• {
• int i;
• cin>>i;
• i=sum(i);
• cout<<i;}
waitheart_iba@yahoo.com
Recursion
• Other Examples:
– Binary Search - searching for an element
– Towers of Hanoi
One Must Move the disks from the A to B with the following rules
1) a disk can be placed in any one , move one at a time
2) No large disk over a small disk
A B C
waitheart_iba@yahoo.com
Binary Search
1 4 7 8 14 16 28 35
1 4 7 8 14 16 28 35
waitheart_iba@yahoo.com
Back Tracking
What is BackTracking?
In this method the algorithm attempts to complete a
solution by constructing partial solutions and
then extends the partial solution toward completion.
When an inconsistency occurs the algorithm 'backs
up'' by removing the most recent construction and
tries another possibility
(This is called backtracking).
waitheart_iba@yahoo.com
Back Tracking
waitheart_iba@yahoo.com
Back Tracking
void AddQueen(void)
{ for (every unguarded position p on the board)
{ Place a queen in position p;
n ++;
if (n == 8) Print the configuration;
else Addqueen();
Remove the queen from position p;
n--;
} }
waitheart_iba@yahoo.com
Look Ahead
123
456
78
A number is moveable if it is adjacent to the empty square.
waitheart_iba@yahoo.com