0064. Minimum Path Sum

64. Minimum Path Sum #

Problem #

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:

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

Problem Summary #

Given an m x n grid containing non-negative integers, find a path from the top-left corner to the bottom-right corner such that the sum of the numbers along the path is minimized. Note: You can only move one step down or right each time.

Solution Approach #

  • Find the path from the top-left corner to the bottom-right corner on the map whose sum of numbers is the smallest, and output the sum.
  • The simplest idea for this problem is to use a two-dimensional array for DP; of course, this is the most primitive approach. Since you can only move down and right, you only need to maintain information for 2 columns, and pushing from the left to the far right will yield the minimum solution. Going one step further, you can directly perform in-place DP in the original array, with space complexity of 0.

Code #


package leetcode

// Solution 1: In-place DP, no auxiliary space
func minPathSum(grid [][]int) int {
	m, n := len(grid), len(grid[0])
	for i := 1; i < m; i++ {
		grid[i][0] += grid[i-1][0]
	}
	for j := 1; j < n; j++ {
		grid[0][j] += grid[0][j-1]
	}
	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			grid[i][j] += min(grid[i-1][j], grid[i][j-1])
		}
	}
	return grid[m-1][n-1]

}

// Solution 2: The most primitive method, auxiliary space O(n^2)
func minPathSum1(grid [][]int) int {
	if len(grid) == 0 {
		return 0
	}
	m, n := len(grid), len(grid[0])
	if m == 0 || n == 0 {
		return 0
	}

	dp := make([][]int, m)
	for i := 0; i < m; i++ {
		dp[i] = make([]int, n)
	}
	// initFirstCol
	for i := 0; i < len(dp); i++ {
		if i == 0 {
			dp[i][0] = grid[i][0]
		} else {
			dp[i][0] = grid[i][0] + dp[i-1][0]
		}
	}
	// initFirstRow
	for i := 0; i < len(dp[0]); i++ {
		if i == 0 {
			dp[0][i] = grid[0][i]
		} else {
			dp[0][i] = grid[0][i] + dp[0][i-1]
		}
	}
	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
		}
	}
	return dp[m-1][n-1]
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文