Minimum Path Sum in a Grid

Problem

Read a grid of positive numbers. You start at the top-left cell and must reach the bottom-right cell. You can only move right or down. Print the smallest possible sum of the numbers on the path (both end cells included).

Constraints

  • 1 <= r, c <= 100
  • 1 <= cell <= 100

Examples

Input

3 3
1 3 1
1 5 1
4 2 1

Output

7

Solutions

Best approachTime O(r * c)Space O(r * c)

Every cell can be reached from the cell above or from the cell on the left. So the cheapest way to a cell is its own number plus the cheaper of these two neighbours.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Cheapest path in a grid.
 * Input   : A matrix.
 * Output  : The smallest sum.
 * Approach: DP over cells.
 * Time    : O(r * c)
 * Space   : O(r * c)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[][] m) {
        int rows = m.length;
        int cols = m[0].length;

        // Step 1: cost[i][j] = the smallest path sum to reach the cell (i, j).
        long[][] cost = new long[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (i == 0 && j == 0) {
                    // Step 2: The start cell costs its own number.
                    cost[i][j] = m[i][j];
                } else if (i == 0) {
                    // Step 3: In the first row we can only come from the left.
                    cost[i][j] = cost[i][j - 1] + m[i][j];
                } else if (j == 0) {
                    // Step 4: In the first column we can only come from above.
                    cost[i][j] = cost[i - 1][j] + m[i][j];
                } else {
                    // Step 5: Otherwise come from above or from the left, whichever is cheaper.
                    cost[i][j] = Math.min(cost[i - 1][j], cost[i][j - 1]) + m[i][j];
                }
            }
        }
        return cost[rows - 1][cols - 1];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int cols = scanner.nextInt();
        int[][] m = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                m[i][j] = scanner.nextInt();
            }
        }
        System.out.println(solve(m));
    }
}
Hints (1)
  1. From which cells can you reach (i, j)?