问题描述
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:
[[1,3,1],
[1,5,1],
[4,2,1]]
解题思路
该问题是给了一个mxn的二维的数组,要求从数组的左上角到达数组的右下角,找到一个做短的路径。即从左上角开始,每次移动一步,只能向右或者是向下,将每次走到的位置的值加起来,使得到达右下角的时候和最小。我们可以从右下往左上移动,每次计算当前点到右下的最短。f[i, j] = grid[i, j] + min(f[i+1,j], f[i,j+1]),下边和右边两条边线进行特殊处理。
代码展示
#include<iostream>
#include<string>
#include<math.h>
#include<limits>
#include<vector>
using namespace std;
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
int m = grid.size();
if (m == 0) { return 0; }
int n = grid[0].size();
if (n == 0) { return 0; }
int sol[m+1][n+1];
sol[m-1][n] = 0;
sol[m][n-1] = 0;
int int_max = numeric_limits<int>::max();
for (int i = m-2; i >= 0; i--) {
sol[i][n] = int_max;
}
for (int j = 0; j < n - 1; j++) {
sol[m][j] = int_max;
}
for (int i = m-1; i >= 0; i--) {
for (int j = n-1; j >= 0; j--) {
sol[i][j] = grid[i][j] + min(sol[i+1][j], sol[i][j+1]);
}
}
return sol[0][0];
}
};
int main(){
int m, n;
cout<<"请输入矩阵的长和宽:";
cin>>m>>n;
vector<vector<int> > grid(m, vector<int>(n));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>grid[i][j];
}
}
Solution solution;
int result=solution.minPathSum(grid) ;
cout<<result<<endl;
}
运行结果展示