题目:
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.
题目解析:
这道题第一眼看到minimum path马上就可以联想到最小生成树,可以将这一个矩阵看成一个邻接矩阵来计算,根据图的最小生成树算法,很快就可以计算出最小路径和。
事实上,最小生成树的Dijkstra算法就是以DP为基础的算法。在探索路径中找到最小的路径和。但这道题其实可以直接的DP算法。
首先,因为每一个方块的最小路径和是和上面和左边的最小路径和有关。写出状态转移方程:
sum[i][j]=minsum[i−1][j]+element[i][j],sum[i][j−1],element[i][j]
根据状态转移方程写出代码:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
if (!m && !n) return 0;
int sums[m][n];
memset(sums, 0, sizeof(sums));
sums[0][0] = grid[0][0];
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (!r && !c) continue;
if (!r) sums[r][c] = grid[r][c] + sums[r][c - 1];
else if (!c) sums[r][c] = grid[r][c] + sums[r - 1][c];
else {
sums[r][c] = min(sums[r - 1][c] + grid[r][c], sums[r][c - 1] + grid[r][c]);
cout << sums[r][c] << ' ';
}
}
cout << endl;
}
return sums[m - 1][n - 1];
}
};