← All problems

64. Minimum Path Sum

MediumOpen on LeetCodeProblem statement

Problem Statement

64. Minimum Path Sum

Medium


Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

 

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

 

Constraints:

Java — bottomUp

Source file
class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int i = m - 1; i >= 0; i--)
            for (int j = n - 1; j >= 0; j--)
                grid[i][j] += i == m - 1 && j == n - 1 ? 0
                        : i == m - 1 ? grid[i][j + 1]
                                : j == n - 1 ? grid[i + 1][j]
                                        : Math.min(grid[i + 1][j], grid[i][j + 1]);
        // for (int i = 0; i < m; i++)
        //     System.out.println(Arrays.toString(grid[i]));
        return grid[0][0];
    }
}