Shortest Path DAG Source to Sink
Given a list of directed edges, a list of lists of costs associated with the list of edges (representing a weighted acyclic graph), and two identifiers A, B in the graph, find the lowest sum path from A to B. Every preceding look up from A to B1, A to B2, etc, should be computed in linear time.
Return the path as a list from A to B.
For example, the given input:
edges = [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'E'], ['B', 'F'],
['C', 'F'], ['D', 'F'], ['D', 'G'], ['E', 'H'], ['F', 'H'],
['F', 'I'], ['F', 'J'], ['G', 'J'], ['H', 'K'], ['H', 'L'],
['I', 'L'], ['J', 'L'], ['J', 'M'], ['K', 'N'], ['L', 'N'],
['M', 'N']]
costs = [2, 1, 3, 5, 2, 7, 6, 4, 2, 5, 3, 2, 3, 8, 6, 1, 9, 7, 1, 2, 4]Should return:
The Idea: This problem can be solved using BFS and dynamic programming. It is actually very similar to seam carving in the sense that the next optimal path is dependent on the optimal paths that came before it.
We the graph below, we begin at source A because it has no dependencies and does not have an optimal path that comes before it. If we follow through using a BFS, we can find the optimal path for preceding nodes because their parent has it's optimum already computed and can be used to solve for the next optimal path. Note that this only works if the topological ordering of the graph also follows the BFS traversal.
For example, consider node F. We can find the optimal path to node F by selecting the minimal path of its neighbors. OPT[f] =min([OPT[B] + edge(B,F), OPT[C] + edge(C,F), OPT[D] + edge(D, F)]). In order to find the edges that lead into F, we can access our inverse graph.
Once the optimal paths from source to every other node is computed, we can backtrack from sink to source to find the minimum path. Consider source node A and sink node N. We know that the OPT[N] = 10, and so the next leading node must be (8) where OPT[x] = OPT[N] - edge(x, N)
Complexity: O(n^2) time of preprocessing, then O(1) to retrieve the distance from source to any node, and O(n) time to obtain the path from source to any node.
Output
Last updated
Was this helpful?