class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
if (!n) return 0;
vector<vector<int>> f(n, vector<int>(m, INT_MAX)); //初始化设置为无穷大
f[0][0] = grid[0][0];
for (int i = 1; i < n; i ++) f[i][0] = f[i - 1][0] + grid[i][0]; // 初始化第一行,每次只能向右移动
for (int j = 1; j < m; j ++) f[0][j] = f[0][j - 1] + grid[0][j]; // 初始化第一列,每次只能向下移动
for (int i = 1; i < n; i ++)
for (int j = 1; j < m; j ++)
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
return f[n - 1][m - 1];
}
};
yxc代码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
if (!n) return 0;
vector<vector<int>> f(n, vector<int>(m, INT_MAX));
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++) {
if (!i && !j) f[i][j] = grid[i][j];
else {
if (i) f[i][j] = min(f[i][j], f[i - 1][j] + grid[i][j]);
if (j) f[i][j] = min(f[i][j], f[i][j - 1] + grid[i][j]);
}
}
return f[n - 1][m - 1];
}
};