Minimum-Cost Path with Fuel Stops on a Grid
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests grid DP with an extra state dimension: navigate an N×M grid from top-left to bottom-right tracking remaining fuel, refueling at marked cells, minimizing total toll cost.
Minimum-Cost Path with Fuel Stops
You are driving a vehicle across a rectangular grid of toll roads. The grid has N rows and M columns. Your vehicle starts at the top-left cell (0, 0) and must reach the bottom-right cell (N-1, M-1), moving only right or down at each step.
Each cell (r, c) has a toll cost given by grid[r][c] (a non-negative integer). You pay the toll when you enter a cell — you do not pay to stand at your starting cell (0, 0).
Your vehicle has a fuel tank with capacity F. You begin with a full tank (F units of fuel). Every move (right or down) consumes exactly 1 unit of fuel. If your fuel reaches 0 and you have not yet arrived at (N-1, M-1), you cannot move further — that path is invalid.
Certain cells are designated fuel stations, given as a list of [r, c] pairs. When you enter a fuel station cell, your tank is immediately refueled to F (full capacity) before any further moves. You pay the toll of the station cell normally.
Your goal is to find the minimum total toll cost of any valid path from (0, 0) to (N-1, M-1).
- If no valid path exists (every path runs out of fuel before reaching the destination), return -1.
- The destination cell
(N-1, M-1)may itself be a fuel station (it doesn't matter, since you stop there). - The starting cell
(0, 0)may be a fuel station; if so, entering it would refuel — but since you start there without "entering," it has no refueling effect (your tank is already full). Its toll is also not paid (you don't enter it).
Constraints
1 ≤ N, M ≤ 401 ≤ F ≤ N + M(fuel capacity; note a full tank is always enough to traverse the shortest possible path with no obstacles ifF = N + M - 2)0 ≤ grid[r][c] ≤ 10000 ≤ len(stations) ≤ N * M- Each element of
stationsis a valid[r, c]within the grid; duplicates instationsare ignored. - There is always at least one cell that is reachable in a single move from
(0, 0)(i.e., N ≥ 1 and M ≥ 1, so the grid is non-trivial when N + M > 1). - When
N = 1andM = 1, the answer is 0 (already at destination, no moves needed).
Examples
Example 1
Input: min_cost_fuel_path([[0, 2, 3], [1, 5, 2], [4, 1, 0]], [[1, 0], [1, 2]], 3)
Output: 6
Example 2
Input: min_cost_fuel_path([[0, 1], [1, 0]], [], 1)
Output: -1
Example 3
Input: min_cost_fuel_path([[0]], [], 1)
Output: 0
Hints
Hint 1
Define your DP state as (row, col, fuel_remaining) and use memoization or a priority-queue (Dijkstra) over this 3-D state space. The number of states is at most N × M × F, which is manageable.
Hint 2
When you enter a fuel-station cell, set the fuel dimension to F before recording the state — this collapses many states and prevents infinite loops.
Hint 3
Use Dijkstra's algorithm treating each (row, col, fuel) triple as a node and edge weights as the toll of the destination cell. This guarantees the minimum-cost path even when toll costs vary.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This is a shortest-path problem on a 3-dimensional state space: (row, col, fuel_remaining). The grid is at most 40×40 and fuel is at most N+M ≤ 80, so the total number of states is at most 40 × 40 × 80 = 128,000 — very tractable.
Algorithm: Dijkstra's Algorithm on the State Graph
We model each triple (r, c, f) as a node in a graph. A directed edge exists from (r, c, f) to (nr, nc, f') when:
(nr, nc)is one step right or down from(r, c),f > 0(there is fuel to make the move),f' = Fif(nr, nc)is a fuel station, otherwisef' = f - 1,- Edge weight =
grid[nr][nc](the toll paid upon entering(nr, nc)).
We run Dijkstra starting from (0, 0, F) with cost 0 (no toll for the starting cell, full tank). The first time we pop the destination cell (N-1, M-1) from the priority queue, we have the minimum cost.
Correctness
- All edge weights (tolls) are non-negative, so Dijkstra is correct.
- The fuel state prevents taking paths that use more than
Fconsecutive moves without hitting a station. - When entering a station, fuel resets to
F, collapsing many fuel levels into one — this keeps the state space bounded and prevents revisiting the same station state expensively.
Edge Cases
- 1×1 grid: return 0 immediately (already at destination).
- No valid path: Dijkstra exhausts all reachable states without ever reaching
(N-1, M-1)→ return -1. - Station at destination: doesn't matter; we stop there.
- Station at start: no effect (we start there without "entering").
Complexity
- States: O(N × M × F)
- Edges per state: O(1) (only 2 directions)
- Dijkstra with binary heap: O(N × M × F × log(N × M × F))
- With N, M ≤ 40 and F ≤ 80: roughly 128,000 states, very fast in practice.
- Space: O(N × M × F) for the distance table and heap.
Reference Solution
from typing import List
import heapq
def min_cost_fuel_path(grid: List[List[int]], stations: List[List[int]], F: int) -> int:
N = len(grid)
M = len(grid[0])
# Trivial case: already at destination
if N == 1 and M == 1:
return 0
station_set = set(tuple(s) for s in stations)
INF = float('inf')
# dist[r][c][f] = min cost to reach (r,c) with f fuel remaining
dist = [[[INF] * (F + 1) for _ in range(M)] for _ in range(N)]
dist[0][0][F] = 0
# min-heap: (cost, row, col, fuel)
heap = [(0, 0, 0, F)]
while heap:
cost, r, c, fuel = heapq.heappop(heap)
if r == N - 1 and c == M - 1:
return cost
if cost > dist[r][c][fuel]:
continue
for dr, dc in ((0, 1), (1, 0)):
nr, nc = r + dr, c + dc
if 0 <= nr < N and 0 <= nc < M:
if fuel == 0:
continue # can't move
new_fuel = fuel - 1
# Refuel if entering a station
if (nr, nc) in station_set:
new_fuel = F
new_cost = cost + grid[nr][nc]
if new_cost < dist[nr][nc][new_fuel]:
dist[nr][nc][new_fuel] = new_cost
heapq.heappush(heap, (new_cost, nr, nc, new_fuel))
return -1