Skip to content
BytePatterns

Cheapest Route Between Two Stops

EasyGraphs#dijkstra#min-heap~20m

Problem

A delivery map has n stops numbered 0 to n - 1 and one-way roads given as [u, v, cost], where every cost is zero or more. Return the cheapest total cost of driving from stop src to stop dst, or -1 if dst cannot be reached.

Examples

Input:  n = 5, roads = [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 3, 5], [3, 4, 3]], src = 0, dst = 4
Output: 7
Why:    0 to 2 to 1 to 3 to 4 costs 1 + 2 + 1 + 3, cheaper than the direct road to 1 that costs 4 on its own
Input:  n = 3, roads = [[0, 1, 2]], src = 0, dst = 2
Output: -1
Why:    no road leads into stop 2
Input:  n = 2, roads = [[0, 1, 5]], src = 1, dst = 1
Output: 0
Why:    edge case, the route is already at its destination

Hints

0 / 3

Stuck on the idea rather than the code? Dijkstra's Algorithm covers it.