Lecture 4 1 2 3 RECURSION BACKTRACKING LOOK
Lecture 4 1) 2) 3) RECURSION BACKTRACKING LOOK AHEAD
Recursion What is Recursion? A recursive function is a function that calls itself. EG: finding the factorial of a number: non-recursive long factorial (long n) Recursive method fact = 1; for (i=1; i<=n; i++) fact = fact*i; return fact; long factorial (long number) { if (number == 1) return 1; else return(number*factorial(number - 1)); } main( ) - Next slide
Recursion main() { int factnum; cin>>num; factnum = factorial(num); cout<<factnum; return 0; } If the number is 5 then process will be 5 * Factorial (5 -1) 4 * Factorial (4 -1) 3 * Factorial (3 -1) 2 * Factorial (2 -1) 1
Recursion • EG 2 : Sum of n Natural Numbers: int sum(n) { int i, sum; { for (i=1; i<=n; i++) if (n==1) return 1; else return( n+ sum(n-1)); } sum = sum+i; return sum; }
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
Binary Search 1 1 4 4 7 7 8 8 14 14 16 16 28 28 35 35
Back Tracking What is Back. Tracking? 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 trys another possibility (This is called backtracking).
Back Tracking Example : 8 queens problem. There is 8 x 8 Chess Board and there are 8 queens All the 8 queens have to be placed on the chess board so that no two queens are on the same row, column and diagonal (ie) no two attack each other
4 Queens Problem
Back Tracking void Add. Queen(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--; } }
Look Ahead · In some games the advantage will always be with the player who can think several moves ahead. • Thus this class of recursive algorithm involves a look ahead procedure which findout possible future moves, evaluates them and then selects the best before carrying out the move.
Look Ahead A general description might be: Void Look. Ahead () { Obtain a stack of possible moves if recursion terminates (the base case) return one move and the value else { for each move on the stack do make the move and Lookahead select the best value return the move and value }}
Look Ahead · Try to apply this to the game of 8. The game consists of a 3 x 3 board containing numbers from 1 to 8 put randomly. Therefore there is one space left for numbers to move. The aim of the game is to move the numbers to rearrange them in the following sequence: 1 2 3 4 5 6 7 8 A number is moveable if it is adjacent to the empty square.
- Slides: 13