Fastest Delivery Route with Fuel Stop Limit
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests the ability to apply Dijkstra's algorithm augmented with a constraint dimension (fuel stops used) to find the minimum-time path in a weighted graph.
Fastest Delivery Route with Fuel Stop Limit
You are routing a delivery truck through a network of warehouses connected by roads. Each road takes a known number of minutes to traverse. The truck starts at warehouse 0 and must reach warehouse n - 1 in the minimum total travel time.
However, the truck has a limited fuel tank and must refuel at designated fuel stations. A fuel station is simply any warehouse whose index appears in the list stations. Warehouse 0 (the start) and warehouse n - 1 (the destination) are never counted as fuel stops, even if they appear in stations.
Every time the truck enters a warehouse that is a fuel station (other than 0 and n - 1), that counts as one fuel stop. The truck may visit the same fuel station multiple times, but each visit counts as a separate stop.
The truck is allowed at most k fuel stops in total along any route. Regardless of fuel stops, the truck can travel any road at any time — the constraint is only on how many times it enters a fuel-station warehouse.
Find the minimum travel time (sum of edge weights) from warehouse 0 to warehouse n - 1 using at most k fuel stops. If no such route exists, return -1.
Input:
n— number of warehouses (nodes), indexed0ton - 1.roads— a list of directed roads, each given as[u, v, t]meaning a one-way road from warehouseuto warehousevtakingtminutes.stations— a list of warehouse indices that are fuel stations (may contain duplicates; treat as a set). Warehouses0andn - 1are excluded from stop-counting even if listed here.k— maximum number of fuel stops allowed (0 means the truck cannot stop at any fuel station).
Output: The minimum travel time as an integer, or -1 if unreachable within the stop limit.
Constraints:
2 ≤ n ≤ 3000 ≤ len(roads) ≤ 2 000- Each road:
0 ≤ u, v ≤ n - 1,u ≠ v,1 ≤ t ≤ 10 000 - There may be multiple roads between the same pair of warehouses (different travel times).
0 ≤ len(stations) ≤ n- Each station index is in
[0, n - 1]. 0 ≤ k ≤ n- The graph is directed.
Examples
Example 1
Input: fastest_delivery(5, [[0, 1, 10], [1, 2, 5], [2, 4, 3], [0, 3, 2], [3, 2, 1], [2, 1, 1]], [2, 3], 1)
Output: 18
Example 2
Input: fastest_delivery(4, [[0, 1, 1], [1, 3, 1], [0, 2, 5], [2, 3, 1]], [1], 0)
Output: 6
Example 3
Input: fastest_delivery(2, [[0, 1, 100]], [], 0)
Output: 100
Hints
Hint 1
Think of the state not just as the current warehouse, but as (current_warehouse, fuel_stops_used_so_far). Run Dijkstra over this 2-D state space.
Hint 2
The priority queue should store (total_time, current_node, stops_used). When you move to a neighbor, check whether it is a fuel station (and not the start/end) to decide whether to increment stops.
Hint 3
Keep a 2-D visited/distance array dist[node][stops] so you don't re-process the same (node, stops) pair with higher or equal cost.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
A standard Dijkstra finds the shortest path in a weighted graph. Here we have an additional resource constraint: at most k fuel stops. The trick is to lift the state space to include the constraint dimension.
State: (current_node, stops_used_so_far)
There are n × (k + 1) possible states. For each state we track the minimum travel time needed to reach it.
Algorithm
- Build a directed adjacency list from
roads. - Mark the fuel-station set as
stations \ {0, n-1}(visits to start and destination do not count). - Initialize
dist[node][stops] = ∞for all states; setdist[0][0] = 0. - Run Dijkstra with a min-heap seeded with
(0, 0, 0)(time=0, node=0, stops=0). - When expanding a state
(time, node, stops):- For each outgoing road
(node → neighbor, t):- Compute
new_stops = stops + (1 if neighbor is a fuel station else 0). - If
new_stops > k, skip (constraint violated). - If
time + t < dist[neighbor][new_stops], relax and push to heap.
- Compute
- For each outgoing road
- The first time we pop node
n - 1from the heap, that is the optimal time (Dijkstra's correctness). Return it. If the heap empties without reachingn - 1, return-1.
Why It Is Correct
Dijkstra is correct for non-negative edge weights. The augmented state space (node, stops) satisfies the same monotonicity: once we pop a state with the minimum time it will never be improved, because all edge weights are positive. The constraint on k is enforced by discarding transitions that would exceed it.
Complexity
- States: O(n · k)
- Edges in state graph: O(E · k) where E =
len(roads) - Time: O(E · k · log(n · k))
- Space: O(n · k + E)
With n ≤ 300, k ≤ 300, E ≤ 2 000, this is comfortably fast.
from typing import List
import heapq
def fastest_delivery(n: int, roads: List[List[int]], stations: List[int], k: int) -> int:
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v, t in roads:
adj[u].append((v, t))
# Fuel stations: exclude start (0) and destination (n-1)
station_set = set(stations) - {0, n - 1}
# dist[node][stops] = best known travel time to reach `node` having used exactly `stops` fuel stops
INF = float('inf')
dist = [[INF] * (k + 1) for _ in range(n)]
dist[0][0] = 0
# Min-heap: (time, node, stops_used)
heap = [(0, 0, 0)]
while heap:
time, node, stops = heapq.heappop(heap)
# Early exit
if node == n - 1:
return time
# Prune if this state is outdated
if time > dist[node][stops]:
continue
for neighbor, t in adj[node]:
new_stops = stops + (1 if neighbor in station_set else 0)
if new_stops > k:
continue
new_time = time + t
if new_time < dist[neighbor][new_stops]:
dist[neighbor][new_stops] = new_time
heapq.heappush(heap, (new_time, neighbor, new_stops))
return -1