call(back)
Algorithms & Data StructureshardSign in to star problems

Cheapest Grid Path With a Fuel Tank

You drive across an m x n grid from the top-left cell to the bottom-right cell, moving up, down, left or right.

  • cost[r][c] is the price paid every time you enter cell (r, c). You also pay cost[0][0] for the starting cell.
  • blocked[r][c] is true for cells that cannot be entered.
  • You start with a full tank of capacity units of fuel. Every move needs one unit and uses it.
  • recharge[r][c] is true for cells that refill the tank to capacity when you arrive on them.

Return the minimum total cost of reaching the bottom-right cell, or -1 if it cannot be reached. Arriving with an empty tank is fine.

cost     = [[1, 1, 1],       blocked: none       capacity = 2
            [1, 9, 1],       recharge: only (0, 2)
            [1, 1, 1]]
answer   = 5    // right, right (refill), down, down

Without the refill at (0, 2) the four moves would need four units of fuel. Up to 40 rows and columns, costs from 0 to 1,000, capacity up to 80. The follow-up: what changes if capacity is enormous?

Hints

Hint 1

The costs differ from cell to cell, so breadth-first search is not enough; this is a shortest-path problem with non-negative weights.

Hint 2

Two arrivals at the same cell are not equivalent if they have different fuel left. Make fuel part of the node: (row, column, fuel).

Hint 3

Entering a recharge cell always leaves you in the state (row, column, capacity), whatever you had before.

Topics

Asked at

Similar Problems6