Minimum Toll Path
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A town map is divided into an grid grid; passing through cell (i, j) costs a toll of grid[i][j].
A traveller starts at the top-left cell (0, 0) and wants to reach the bottom-right cell (H-1, W-1), moving only
right or down one cell at a time. Return the minimum possible sum of tolls of all visited cells, including the start and the end.
Examples
| grid | result |
|---|---|
[[1, 3, 1], [1, 5, 1], [4, 2, 1]] | 7 |
[[1, 2, 3], [4, 5, 6]] | 12 |
[[5]] | 5 |
Example 1 — Right, right, down, down: 1 + 3 + 1 + 1 + 1 = 7.
Example 2 — Along the top row, then down: 1 + 2 + 3 + 6 = 12.
Example 3 — The start is also the destination.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(grid: int[][]) → int
Constraints
- , (
gridis an rectangle) -
grid[i][j]
Expected complexity
- Time
- O(HW)
- Space
- O(W)
Examples
| grid | Expected |
|---|---|
[[1,3,1],[1,5,1],[4,2,1]] | 7 |
[[1,2,3],[4,5,6]] | 12 |
[[5]] | 5 |
Hint
Hint
A cell can only be entered from above or from the left, so best[i][j] = grid[i][j] + min(best[i-1][j], best[i][j-1])
(the first row and column have a single predecessor). Following every path recursively explores paths;
filling the table row by row is and one row of memory is enough.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1040 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 4 | verdict only |