Download presentation
Presentation is loading. Please wait.
Published byCaren Burns Modified over 8 years ago
1
CSE 3358 NOTE SET 8 Data Structures and Algorithms
2
Finding a Path Backtracking – a method to try all possible paths in an orderly fashion. Exhaustive search Stop when a path is located Not looking for the “shortest” path yet. Intuition: Try all paths leading from the origination city. From each of those cities, try all paths leading from each of them. Continue until a path is found
3
Simple Example A B C D Requested Flight: City A City D Use a stack to hold the path you’re currently trying.
4
Example 2 Requested Flight: City A City F A B C E D F
5
Example 3 A B C E D Requested Flight: City A City E
6
General Idea Initialize Stack Loop while the stack isn’t empty and the top of the stack isn’t the destination If need to backtrack from the city on top of stack pop off the stack Else Select a destination city from city on top of stack that hasn’t already been visited Push that city on to the stack End if End Loop
7
Example – Adjacency List A B C D A B, C B ~ C D D ~
8
Recursion Review Base Case Recursive Case Uses call stack to store values of local variables while new method invocation is executing Activation record on stack Values for parameters Local variables (or pointers to them) Return address of where to resume Pointer to caller’s activation record Return value if needed/present
9
Tail Recursion Only one recursive call at the very end of a function implementation void tail (int i) { if (i > 0) { cout << i << ‘ ‘; tail(i – 1); } void nonTail (int i) { if (i > 0) { tail(i – 1); cout << i << ‘ ‘; tail(i – 1); }
10
Tail Recursion Tail Recursion is a “glorified loop” Advantages: Some languages don’t have looping constructs void tail (int i) { if (i > 0) { cout << i << ‘ ‘; tail(i – 1); } void iterative (int i) { for (; i > 0; i--) cout << i << ‘ ‘; }
11
Non-tail Recursion Makes use of the fact that the activation record is on the stack Iterative transformation typically requires handling of a stack structure void reverse() { char ch; cin.get(ch); if (ch != ‘\n’) { reverse(); cout.put(ch); }
12
Non-tail Recursion void reverse() { char ch; cin.get(ch); if (ch != ‘\n’) { reverse(); cout.put(ch); } void iterativeReverse() { char ch; cin.get(ch); while (ch != ‘\n’) { stack.push(ch); cin.get(ch); } while(!stack.isEmpty()) { cout << stack.top() << ‘ ‘; stack.pop(); }
13
Indirect Recursion f() g() h() f() g()…… Mathematical Example When do we stop?
14
?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.