My code:
public class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
if (grid.length == 1 && grid[0].length == 1)
return grid[0][0];
int row = grid.length;
int col = grid[0].length;
for (int i = 1; i < col; i++)
grid[0][i] += grid[0][i - 1];
for (int i = 1; i < row; i++)
grid[i][0] += grid[i - 1][0];
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (grid[i][j - 1] < grid[i - 1][j])
grid[i][j] += grid[i][j - 1];
else
grid[i][j] += grid[i - 1][j];
}
}
return grid[row - 1][col - 1];
}
}
My test result:
![Upload Paste_Image.png failed. Please try again.]
这次题目不是很难,主要使用到了贪婪的思想。
Greedy Algorithm.
从(1,1) 开始,我要保证每个格点的数值,是起点到这里的最近距离。
于是可以从(1,1) -> (1,col - 1)遍历。
然后再从 (2, 1) -> (2, col - 1)遍历。
然后不断刷新最短距离。如下图示例。
![Upload Paste_Image.png failed. Please try again.]
**
总结:Array, Greedy Algorithm, DP
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0)
return -1;
/** add row */
for (int i = 1; i < grid[0].length; i++)
grid[0][i] += grid[0][i - 1];
/** add col */
for (int i = 1; i < grid.length; i++)
grid[i][0] += grid[i - 1][0];
/** deal with inner matrix */
for (int i = 1; i < grid.length; i++) {
for (int j = 1; j < grid[0].length; j++) {
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
}
一遍过。也没什么可说的。不难。
Anyway, Good luck, Richardo!
差不多的思路。
Anyway, Good luck, Richardo! -- 08/07/2016