class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if (grid.size() == 0) {
return 0;
}
int m = grid.size();
int n = grid[0].size();
//dp: 每格的值 = min(上, 左) + 自己
vector<vector<int>> minVal(m, vector<int>(n, 0));
minVal[0][0] = grid[0][0];
//bottom
for (int i = 1; i < m; i++) {
minVal[i][0] = minVal[i - 1][0] + grid[i][0];
}
//left
for (int j = 1; j < n; j++) {
minVal[0][j] = minVal[0][j - 1] + grid[0][j];
}
//middle
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
minVal[i][j] = min(minVal[i - 1][j], minVal[i][j - 1]) + grid[i][j];
}
}
return minVal[m - 1][n - 1];
}
};