A maze is a grid with rows rows and cols columns. Cell (i, j) is either blocked
(marked -1, impassable) or open, in which case it has an energy cost between 0 and 1000 to enter.
The top-left cell (0, 0) and the bottom-right cell (rows - 1, cols - 1) are always open. From any
open cell you may move to any of the (up to four) adjacent open cells: up, down, left, or right (no
diagonal moves).
Print the minimum total energy cost of a route from (0, 0) to (rows - 1, cols - 1), summing the
cost of every cell visited along the way (including the start and end cells). If no such route exists,
print -1 instead.
Line 1: two integers rows cols.
Next rows lines: cols space-separated integers each -- -1 for a blocked cell, otherwise the
energy cost of that cell.
A single integer: the minimum total energy cost of a route from the top-left to the bottom-right cell,
or -1 if no route exists.
-1 or an integer between 0 and 1000-1Example 1
Input
2 2 1 1 -1 1
Expected
3
Explanation
Cell (1,0) is blocked, so the only route is right then down through cells costing 1, 1 and 1, for a total of 3.
Example 2
Input
2 2 1 -1 -1 1
Expected
-1
Explanation
Every neighbor of the start and end cells is blocked, so there is no way to reach the bottom-right cell, giving -1.
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 →