Skip to content

Cheapest Route Between Two Stops

Easy#dijkstra#min-heap~20 min

The mission

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

Target time
O((n + m) log n)
Target space
O(n + m)

Constraints

  • stops are numbered 0 to n - 1
  • roads are one-way
  • every cost ≥ 0

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

Python 3Ctrl+Enter runs
Custom test case