0
votes

You have a 2005 Honda Accord with 50 miles (weight max) left in the tank. Which McDonalds locations (graph nodes) can you visit within a 50 mile radius? This is my question.

If you have a weighted directed acyclic graph, how can you find all the nodes that can be visited within a given weight restriction?

I am aware of Dijkstra's algorithm but I can't seem to find any documentation of its uses outside of min-path problems. In my example, theres no node in particular that we want to end at, we just want to go as far as we can without going over the maximum weight. It seems like you should be able to use BFS/DFS in order to solve this, but I cant find documentation for implementing those in graphs with edge weights (again, outside of min-path problems).

2

2 Answers

0
votes

Finding the longest path to a vertex V (a McDonald's in this case) can be accomplished using topological sort. We can start by sorting our nodes topologically, since sorting topologically will always return the source node U, before the endpoint, V, of a weighted path. Then, since we would now have access to an array in which each source vertex precedes all of its adjacent vertices, we can search through every path beginning with vertex U and ending with vertex V and set a value in an array with an index corresponding to U to the maximum edge weight we find connecting U to V. If the sum of the maximal distances exceeds 50 without reaching a McDonalds, we can backtrack and explore the second highest weight path going from U to V, and continue backtracking should we exhaust every path exiting from vertex U. Eventually we will arrive at a McDonalds, which will be the McDonalds with the maximal distance from our original source node while maintaining a total spanning distance under 50.

0
votes

For this problem, you will want to run a DFS from the starting node. Recurse down the graph from each child of the starting node until a total weight of over 50 is reached. If a McDonalds is encountered along the traversal record the node reached in a list or set. By doing so, you will achieve the most efficient algorithm possible as you will not have to create a complete topological sort as the other answer to this question proposes. Even though this algorithm still technically runs in O(ElogV) time, by recursing back on the DFS when a path distance of over 50 is reached you avoid traversing through the entire graph when not necessary.