intermediate · dynamic programming · grid · tabulation

The cheapest walk down and right

Problem

A courier crosses a city laid out as a rectangular grid of blocks. Each block has a toll (a non-negative whole number). The courier starts at the top-left block, ends at the bottom-right block, and may only move one block right or one block down at a time. Every block entered, including the first and the last, charges its toll.

Return the smallest total toll. In the lab the grid is given row by row as one list, with its width.

Constraints

  • 1 ≤ rows · columns ≤ 30, width 1 to 8 (visualization limit)
  • tolls from 0 to 99

Examples

grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]] → 7 — Right, right, down, down: 1 + 3 + 1 + 1 + 1.

Show the solution

Row-by-row table

The cheapest walk to a block is the cheaper of the cheapest walks to its two possible predecessors, plus its own toll. Filling in reading order guarantees both predecessors are done.

Why it is correct

Induction in reading order. Any walk to (r, c) other than the start ends with a move from (r − 1, c) or (r, c − 1); its cost is that walk's cost plus toll[r][c], which is at least cost[predecessor] + toll[r][c]. Taking the cheaper predecessor achieves the minimum. Both predecessors come earlier in reading order, so their entries are final.

Complexity

Time O(rows · columns), extra space O(rows · columns), or O(columns) keeping one row. One constant-time update per block.

For contrast: Recursively try both moves from every block. That costs O(2^(rows + columns)) time and O(rows + columns) space.

Edge cases

  • A single block: its toll.
  • A single row or column: the sum of all tolls.
  • Zero tolls create ties; any cheapest walk is fine.

Common mistakes

  • Forgetting the start block's own toll.
  • Treating out-of-grid predecessors as cost 0 instead of unavailable.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class MinPathSum
{
    /// <summary>Cheapest top-left to bottom-right walk moving right or down, paying every toll entered. O(rows * cols).</summary>
    public static int Cheapest(int[][] tolls)
    {
        int rows = tolls.Length, cols = tolls[0].Length;
        var cost = tolls.Select(row => (int[])row.Clone()).ToArray(); // cost[r][c]: cheapest walk ending at (r, c)
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                if (r == 0 && c == 0) continue;
                int up = r > 0 ? cost[r - 1][c] : int.MaxValue;
                int left = c > 0 ? cost[r][c - 1] : int.MaxValue;
                cost[r][c] += Math.Min(up, left);
            }
        }
        return cost[rows - 1][cols - 1];
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/MinPathSum.cs

import math
from collections.abc import Sequence
 
 
def cheapest(tolls: Sequence[Sequence[int]]) -> int:
    """Cheapest top-left to bottom-right walk moving right or down, paying every toll entered. O(rows * cols)."""
    rows, cols = len(tolls), len(tolls[0])
    cost = [list(row) for row in tolls]  # cost[r][c]: cheapest walk ending at (r, c)
    for r in range(rows):
        for c in range(cols):
            if r == 0 and c == 0:
                continue
            up = cost[r - 1][c] if r > 0 else math.inf
            left = cost[r][c - 1] if c > 0 else math.inf
            cost[r][c] += int(min(up, left))
    return cost[rows - 1][cols - 1]

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/min_path_sum.py

package dev.bekadan.dsa.problems;
 
public final class MinPathSum {
    private MinPathSum() {
    }
 
    /** Cheapest top-left to bottom-right walk moving right or down, paying every toll entered. O(rows * cols). */
    public static int cheapest(int[][] tolls) {
        int rows = tolls.length;
        int cols = tolls[0].length;
        int[][] cost = new int[rows][]; // cost[r][c]: cheapest walk ending at (r, c)
        for (int r = 0; r < rows; r++) {
            cost[r] = tolls[r].clone();
        }
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (r == 0 && c == 0) {
                    continue;
                }
                int up = r > 0 ? cost[r - 1][c] : Integer.MAX_VALUE;
                int left = c > 0 ? cost[r][c - 1] : Integer.MAX_VALUE;
                cost[r][c] += Math.min(up, left);
            }
        }
        return cost[rows - 1][cols - 1];
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/MinPathSum.java

#pragma once
 
#include <algorithm>
#include <climits>
#include <cstddef>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// Cheapest top-left to bottom-right walk moving right or down, paying every toll entered. O(rows * cols).
inline int min_path_sum(const std::vector<std::vector<int>>& tolls) {
    const std::size_t rows = tolls.size(), cols = tolls[0].size();
    auto cost = tolls;  // cost[r][c]: cheapest walk ending at (r, c)
    for (std::size_t r = 0; r < rows; ++r) {
        for (std::size_t c = 0; c < cols; ++c) {
            if (r == 0 && c == 0) continue;
            const int up = r > 0 ? cost[r - 1][c] : INT_MAX;
            const int left = c > 0 ? cost[r][c - 1] : INT_MAX;
            cost[r][c] += std::min(up, left);
        }
    }
    return cost[rows - 1][cols - 1];
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/min_path_sum.hpp