Homework 6 Shortest Paths!
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.
Why Should I Care? In life, there are many situations where you want to find the shortest path between two nodes:
Planning the Fastest Subway Ride...
Finding the Winning Series of Moves in a Game...
BFS versus Shortest Path
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.
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; //... }
More steps: Make sure BinaryNode implements Comparable, using distance values to compare nodes. TreeNode should be a generic class.
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. }
This is a simplified version of Dijkstra's Algorithm Dijkstra was one of the “giants” who created modern CS.
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.
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.
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 ) )