816. Plan the cheapest tool chain with Dijkstra
Why it matters Tool-using agents and workflow planners route between formats and services by cost, which is a shortest path problem.
An agent can turn one artefact into another with tools (pdf -> text, text -> summary, audio -> text), and each tool has a cost. The cheapest way from what you have to what you need is a shortest path.
Write cheapest_chain(tools, start, goal). tools is a list of (name, src, dst, cost) with cost >= 0. Return (total_cost, [tool names in order]) for the cheapest path from start to goal using Dijkstra's algorithm, or (None, []) if goal cannot be reached. If start == goal return (0, []). When two paths cost the same, prefer the one whose list of tool names is smaller in Python list order.
def cheapest_chain(tools, start, goal)Example 1
Input: cheapest_chain([('a', 'x', 'y', 1), ('b', 'y', 'z', 1), ('c', 'x', 'z', 5)], 'x', 'z')
Output: (2, ['a', 'b'])
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Build an adjacency list from src to (dst, cost, name).
Hint 2
Use heapq with (cost, path, node) so ties compare paths.
Hint 3
Mark a node done when it is popped, not when it is pushed.
Common mistakes
- Breadth-first search, which finds the fewest tools rather than the cheapest.
- Marking nodes visited at push time, which can lock in a costlier path.
Understand the idea
Dijkstra always expands the cheapest frontier node next. With non-negative costs, the first time the goal is popped its cost is optimal. Putting the path into the heap entry after the cost makes ties fall back to comparing tool name lists.
x -> y -> z costs 2, beating the direct tool at 5.
pop (cost, path, node); skip if done; return on goal; push neighbours