Recursive Algorithms in Java: ForestItem Grid and Maze Solver
90 likes | 190 Vues
Explore recursion concepts through ForestItem grid implementation to solve mazes. Includes examples of calculating sum and Fibonacci numbers recursively, enhancing understanding of complex programming techniques.
Recursive Algorithms in Java: ForestItem Grid and Maze Solver
E N D
Presentation Transcript
CPSC 233 Tutorial Xin Mar 7, 2011
A trap in Asgn 4 • Each element of the grid is a reference to ForestItem, not a character • Different from the example program • Define class ForestItem, and used it in the grid!!!
Recursion • The concept • Call itself inside a function • Components • A method definition • Call itself inside the method with a smaller-scaled argument • An ending condition int sum (intarg) { if (arg > 0) return sum (arg – 1) + arg; else return 0; }
What’s good? • Logically simple program (for certain problems) • What’s bad? • Hard to understand for new learners • Spend some time to feel comfortable with it • Believe the function works • Don’t confuse yourself by expanding the recursion • memory consuming
Example 1 -- SUM public class sum { intsumup(intn) { if (n > 0) return sumup (n - 1) + n; else return 0; } } public class sum_driver { public static void main (String args []) { sum aSum = new sum(); intn = 10; System.out.println("the sum from 0 to " + n + " is " + aSum.sumup(n)); } }
Example 2 – Fibonacci number • Definition • F (n) = F (n - 1) + F (n – 2) • F (0) = 0; F(1) = 1;
Example 2 -- code public class fibonacci { int fib (intn) { if (n < 0) { System.out.println ("n must be non-negative"); return 0; } else if (n == 0) return 0; else if (n == 1) return 1; else return fib ( n - 1) + fib (n - 2); } } public class fibonacci_driver { public static void main (String args []) { fibonacciaFib = new fibonacci(); intn = 10; System.out.println ("fibonacci(" + n + ") is " + aFib.fib(n)); } }
Maze Solver • The idea: • Try an immediate neighbor • Accessible in one step • Is there a way from that neighbor to the EXIT? • Call recursively
Improve grid programMove the party n = (dy + 1) * 3 + (dx + 1) dx = (n – 1) % 3 - 1 dy = (n – 1) / 3 - 1