A maintenance cart must travel across a service floor from the top-left cell (0, 0) to the bottom-right cell (rows-1, cols-1). The floor is a grid where each cell either costs a fixed amount of fuel to enter, or is impassable. Normally the cart may only move one cell right or one cell down at a time, paying the fuel cost of the cell it enters (including the starting cell). As a special allowance, the cart is permitted to use at most one diagonal shortcut during the entire trip: a single move from a cell (r, c) directly to (r+1, c+1), paying only the fuel cost of (r+1, c+1) (no cost is paid for skipping the intermediate cell). The cart may choose not to use the shortcut at all.
Find the minimum total fuel cost to travel from (0, 0) to (rows-1, cols-1).
Line 1: two integers rows and cols.
Each of the next rows lines: cols space-separated integers. A value of -1 means the cell is impassable (can never be entered, by any kind of move); any other value v (0 <= v <= 999) means the cell costs v fuel to enter.
Print a single integer: the minimum total fuel cost of a route from (0, 0) to (rows-1, cols-1) using right moves, down moves, and at most one diagonal (down-right) move. If (0, 0) or (rows-1, cols-1) is impassable, or no route exists, print -1.
-1 or an integer in [0, 999]Example 1
Input
2 2 0 9 9 0
Expected
0
Explanation
Going right then down costs 0+9+0=9, and down then right also costs 9, but the diagonal shortcut goes straight from (0,0) to (1,1), paying only the destination's cost of 0, for a total of 0.
Example 2
Input
1 3 2 5 1
Expected
8
Explanation
There is only one row, so no diagonal move is ever possible; the cart must move right twice, paying 2 + 5 + 1 = 8.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →