Recursion When to use it and when not to use it. Basics of Recursion Recursion uses a method Recursion uses a method Within that method a call is made.

Slides:



Advertisements
Similar presentations
Heuristics, and what to do if you dont know what to do Carl Hultquist.
Advertisements

Solving N+k Queens Using Dancing Links Matthew A. Wolff Morehead State University May 19, 2006.
§3 Dynamic Programming Use a table instead of recursion 1. Fibonacci Numbers: F(N) = F(N – 1) + F(N – 2) int Fib( int N ) { if ( N
CHAPTER 2 ALGORITHM ANALYSIS 【 Definition 】 An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition,
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
The N-Queens Problem lab01.
CS 61B Data Structures and Programming Methodology July 31, 2008 David Sun.
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Fall 2008Programming Development Techniques 1 Topic 3 Linear Recursion and Iteration September 2008.
CPSC 311, Fall 2009: Dynamic Programming 1 CPSC 311 Analysis of Algorithms Dynamic Programming Prof. Jennifer Welch Fall 2009.
Binary Search Introduction to Trees. Binary searching & introduction to trees 2 CMPS 12B, UC Santa Cruz Last time: recursion In the last lecture, we learned.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Blind Search-Part 2 Ref: Chapter 2. Search Trees The search for a solution can be described by a tree - each node represents one state. The path from.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
The Power of Calling a Method from Itself Svetlin Nakov Telerik Corporation
Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer The Power of the Recursive Algorithms.
Recursion Chapter 5.
Solving Sudoku Mark PTTLS Micro teach. Solving Sudoku What is a Sudoku? A Sudoku is a number puzzle based on a 9x9 grid made up from smaller 3x3 blocks.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Glen Martin - School for the Talented and Gifted - DISD Recursion Recursion Recursion Recursion Recursion Recursion.
ADA: 7. Dynamic Prog.1 Objective o introduce DP, its two hallmarks, and two major programming techniques o look at two examples: the fibonacci.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2008 Dynamic programming  top-down vs. bottom-up  divide & conquer vs. dynamic programming  examples:
NxN Queens Problem Q- -- -Q Q- -- -Q Q- -- QQ -- Q- Q- Q- -Q QQ -- -Q -- -Q Q- -Q -Q Q- Q- -Q Q- -- Q- -- QQ Q- -Q -Q -Q -- QQ -- -Q START.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Computer Science Club It is easier to change the specification to fit the program than vice versa.
State-Space Searches. 2 State spaces A state space consists of A (possibly infinite) set of states The start state represents the initial problem Each.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Data Structures Using C++ 2E1 Recursion and Backtracking: DFS Depth first search (a way to traverse a tree or graph) Backtracking can be regarded as a.
Dynamic Programming. Algorithm Design Techniques We will cover in this class: ◦ Greedy Algorithms ◦ Divide and Conquer Algorithms ◦ Dynamic Programming.
CSIS 113A Lecture 5 Random Numbers, while, do-while.
Dynamic Programming Louis Siu What is Dynamic Programming (DP)? Not a single algorithm A technique for speeding up algorithms (making use of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
§5 Backtracking Algorithms A sure-fire way to find the answer to a problem is to make a list of all candidate answers, examine each, and following the.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Chapter 13 Backtracking Introduction The 3-coloring problem
An Analysis of the n- Queens problem Saleem Karamali.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Recursion ITFN The Stack. A data structure maintained by each program at runtime. Push Pop.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
 Chapter 7 introduces the stack data type.  Several example applications of stacks are given in that chapter.  This presentation shows another use called.
Recursion ● Recursion or Iteration ● A Common Recursive Design Pattern ● Computing factorials ● Searching a filesystem tree ● Faster exponentiation ● Slow.
CSG3F3/ Desain dan Analisis Algoritma
Recursion Data Structure Submitted By:- Dheeraj Kataria.
Year 5 - Numeracy Title page..
Computer Science 4 Mr. Gerb
CSCI 104 Backtracking Search
Sit-In Lab 1 Ob-CHESS-ion
Using a Stack Chapter 6 introduces the stack data type.
Recursion Copyright (c) Pearson All rights reserved.
Applied Algorithms (Lecture 17) Recursion Fall-23
Chapter 12 Recursion (methods calling themselves)
Using a Stack Chapter 6 introduces the stack data type.
The Power of Calling a Method from Itself
Stacks.
adapted from Recursive Backtracking by Mike Scott, UT Austin
Stack Frames and Functions
Using a Stack Chapter 6 introduces the stack data type.
Using a Stack Chapter 6 introduces the stack data type.
Tree Searching.
Tree Searching.
The N-Queens Problem Search The N-Queens Problem Most slides from Milos Hauskrecht.
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Presentation transcript:

Recursion When to use it and when not to use it

Basics of Recursion Recursion uses a method Recursion uses a method Within that method a call is made to the same method Within that method a call is made to the same method Somewhere within the method, the loop must be exited Somewhere within the method, the loop must be exited

Disadvantages 3 major disadvantages 3 major disadvantages Slow algorithms Slow algorithms e.g. recursive Fibonacci: e.g. recursive Fibonacci: 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. Procedure call overheads: 30% slower Procedure call overheads: 30% slower Not much time lost though Not much time lost though Data on stack (stack overflow) Data on stack (stack overflow) Not much of a problem these days Not much of a problem these days Watch out for using more than the limit Watch out for using more than the limit

Disadvantages Summary The first one is the one to watch out for (slower algorithms) The first one is the one to watch out for (slower algorithms) The other two can almost be ignored (procedure call overheads and data on stack) The other two can almost be ignored (procedure call overheads and data on stack)

What to Use Instead If iteration is easy to program, use it If iteration is easy to program, use it If dynamic programming works, use it instead If dynamic programming works, use it instead

Why Use Recursion? Easy to program Easy to program Easy to debug Easy to debug Shorter than dynamic programming Shorter than dynamic programming

n Queens Problem Place n queens on an n x n chess board so that no queen is attacked by another queen Place n queens on an n x n chess board so that no queen is attacked by another queen Find out the total number of configurations Find out the total number of configurations

n Queens Solution The most obvious solution is to recursively add queens, trying all possible placements The most obvious solution is to recursively add queens, trying all possible placements It is easy to see that there can only be one queen per column It is easy to see that there can only be one queen per column At each step, you know the position of the queens for the first i columns At each step, you know the position of the queens for the first i columns

n Queens Solution Cont. You try to place a queen in the i + 1 column You try to place a queen in the i + 1 column If successful, you move on to the next step, trying to place a queen in the i + 2 column If successful, you move on to the next step, trying to place a queen in the i + 2 column

n Queens Solution Cont. QQXQXQX  X  X  X  QQXX XQ QXQXQXQX Q  QX  X  X  XXX QQXQXX

XQQXX QX  Q  QX  QX  XQXX QQQXQX XXQQX QX  X  X  XQQQX XQ

QQXQXX Q  X  X  X  QQXQXQX QQXXX XQQXQX X  X  X  XQQX QQQQX

QXXXX FINISHED X  Q  QX  X  XXX QXQQXQX

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 Cont. The not_attacked method simply checks to see if the queen can be placed in that particular block The not_attacked method simply checks to see if the queen can be placed in that particular block

n Queens Analysis Since the number of possibilities is small, recursion is quick enough in this case Since the number of possibilities is small, recursion is quick enough in this case For a 10 x 10 board it runs for 0.11 s For a 10 x 10 board it runs for 0.11 s This solution is also an example of depth first search This solution is also an example of depth first search In questions similar to this, use recursion, since it is easier to program In questions similar to this, use recursion, since it is easier to program

Little Flower Shop IOI ’99 You want to arrange the window of your flower shop in a most pleasant way. You have F bunches of flowers, each being of a different kind and at least as many vases (V) ordered in a row. You want to arrange the window of your flower shop in a most pleasant way. You have F bunches of flowers, each being of a different kind and at least as many vases (V) ordered in a row. The bunches are moveable and are uniquely identified by integers between 1 and F. These id-numbers have a significance. They determine the required order of appearance of the flower bunches in the row of vases. The bunch i must be on the left of bunch j whenever i < j. The bunches are moveable and are uniquely identified by integers between 1 and F. These id-numbers have a significance. They determine the required order of appearance of the flower bunches in the row of vases. The bunch i must be on the left of bunch j whenever i < j. Excess vases will be left empty. A vase can only hold one bunch of flowers. Excess vases will be left empty. A vase can only hold one bunch of flowers.

Little Flower Shop Cont. Each vase has a distinct characteristic (just like flowers do). Hence, putting a bunch of flowers in a vase results in a certain aesthetic value. These values are presented in the following table: Each vase has a distinct characteristic (just like flowers do). Hence, putting a bunch of flowers in a vase results in a certain aesthetic value. These values are presented in the following table: VASES FLOWERS

Flower 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 Analysis In the initial problem, the vase numbers must also be output In the initial problem, the vase numbers must also be output It is far too slow It is far too slow It tries every solution to find the maximum It tries every solution to find the maximum

Flower Solution 2 The first solution was too slow The first solution was too slow This time we’ll try dynamic programming This time we’ll try dynamic programming Start from the second-last row Start from the second-last row Scan each row from left to right Scan each row from left to right Add the maximum value in each block Add the maximum value in each block

Flower Solution 2 Cont. int m; int m; 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 Cont. int answer = ; int answer = ; for (int i = 0; i < F; i++) ans = max (ans, grid [0][i]); ans = max (ans, grid [0][i]);

Flower Solution 2 Cont. The solution is illustrated in the tables on the right The solution is illustrated in the tables on the right The top table is before The top table is before The bottom table is after The bottom table is after Yellow numbers were changed Yellow numbers were changed

Flower Solution 2 Analysis Only the necessary calculations are done Only the necessary calculations are done Much faster algorithm (0.05 s, quicker than 2 s allowed) Much faster algorithm (0.05 s, quicker than 2 s allowed) To determine the vase numbers is easy To determine the vase numbers is easy

Flower Analysis In this case, recursion is not fast enough In this case, recursion is not fast enough As always, if dynamic programming works, use it As always, if dynamic programming works, use it Not all problems can be solved with dynamic programming, since it uses more memory Not all problems can be solved with dynamic programming, since it uses more memory

Conclusion When recursion runs within the time limit, use it When recursion runs within the time limit, use it If it doesn’t, try using dynamic programming or another technique If it doesn’t, try using dynamic programming or another technique If you can’t do it any other way, use recursion to get partial marks If you can’t do it any other way, use recursion to get partial marks

Conclusion Cont. Remember, many other techniques use recursion, so it is important to know well Remember, many other techniques use recursion, so it is important to know well Most graph theory (shortest paths, etc.) uses recursion Most graph theory (shortest paths, etc.) uses recursion