Leetcode-Minimum Path Sum, leetcodepathsum
Minimum Path Sum
Question:
Given a square, each square has a number. Now we need to find a path starting from the upper left corner of the square until the lower right corner of the square. The condition is that the sum of the numbers passing through this path is the minimum.
Solution:
This question is still a problem of the dynamic planning type. The key is how we divide this question into multiple similar stages.
The current idea is that you can first find the minimum path in the small square, and then use the current result to find the smallest path in the square larger than him. If so, will the smallest path of the big square pass through the smallest path of the small square? (Will it reach the upper left corner of the small square ?) This cannot be determined yet.
I derived another method from the previous idea. First, we observe the number of Blocks Affected by each step, and we will find that with the increase of the path length, we push up in a step shape (Suppose we look for it from the bottom right to the top left ). Like this:
OOO OOX OXX XXX
OOO> OOX> OXX> XXX
OOX OXX XXX
According to the idea of dynamic planning, in each stage, we can mark the number of squares in the Cross area as the shortest path length to reach the current square from the bottom right corner. Layer by layer, so there is the current
Matrix [I] [j] = min (matrix [I-1] [j], matrix [I] [J-1])
Suppose we have a matrix as follows:
S50
160
43E
First, we first update the Shortest Path of the two sides in the bottom right corner of the matrix, and then update the matrix in sequence:
S50 S50 S50 (S + 5) 50
160> 190> 890> 8 90
73E 73E 73E 7 3E
So we can write the program as follows:
class Solution: # @param {integer[][]} grid # @return {integer} def minPathSum(self, grid): m = len(grid) n = len(grid[0]) for i in range(1,m): grid[i][0] += grid[i-1][0] for j in range(1,n): grid[0][j] += grid[0][j-1] for i in range(1,m): for j in range(1,n): grid[i][j] += min(grid[i-1][j], grid[i][j-1]) return grid[-1][-1]