Download presentation
Presentation is loading. Please wait.
Published byGordon Ray Modified over 8 years ago
1
Homework 6 Shortest Paths!
2
The Basic Idea You have seen BFS and DFS tree searches. These are nice, but if we add the concept of “distance”, we can get some very useful algorithms.
3
Why Should I Care? In life, there are many situations where you want to find the shortest path between two nodes:
4
Planning the Fastest Subway Ride...
5
Finding the Winning Series of Moves in a Game...
6
BFS versus Shortest Path
7
Your Assignment Implement a “shortest path” search on a tree. Every node will contain a character and a numeric value representing its distance from its parent.
8
First, you should modify the binary tree class so that it can store distances. This can be done simply by adding an extra field in BinaryNode: public class TreeNode { //... double distance; //... }
9
More steps: Make sure BinaryNode implements Comparable, using distance values to compare nodes. TreeNode should be a generic class.
10
Next, modify BFS using the following pseudo-code: findClosest(Node root, Object target) { make new min-heap and insert root with distance 0. while min-heap is not empty { q <- get min element while q not null, and q does not hold target: place q's children into heap, using distance from root as the sort key. }
11
This is a simplified version of Dijkstra's Algorithm Dijkstra was one of the “giants” who created modern CS.
12
Reading input: Input will be of the form: a 0 ( b 3 c 7 ( d 1 e 3 ) ) You will read it from right to left, building a binary tree with rightmost nodes in parentheses being the children of the node to their left. For now, you can ignore the left parens.
13
Read Input and Build A Tree After reading the input and building the tree, your program should search for the node containing the string “*” that has the shortest distance from the root. So, given the following input: a 0 ( b 4 ( * 100 b 6 ) w 9 (x 3 y 5 ( * 2 z 3 ) ) ) Your output should look like: Found "*" at distance 16.
14
Optional Bonus Feature Ambitious students have the option of making their tree support arbitrary numbers of children, rather than simply be a binary tree. This would be done by not ignoring the left parentheses when scanning the input text. Example non-binary input: a 0 (b 3 c 8 ( f 3 g 2 ) d 3 ( e 3 ) )
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.