-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path64最小路径和.java
76 lines (66 loc) · 1.76 KB
/
64最小路径和.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
int[][] grid= new int[][]{{1,3,1},{1,5,1},{4,2,1}};
System.out.println(s.minPathSum(grid));
}
}
//直接在原数组上进行修改
class Solution {
public int minPathSum(int[][] grid) {
if(grid==null || grid.length==0){
return 0;
}
int row = grid.length;
int clo = grid[0].length;
for(int i=1;i<row;i++){
grid[i][0] += grid[i-1][0];
}
for(int j=1;j<clo;j++){
grid[0][j] += grid[0][j-1];
}
//计算
for(int i=1;i<row;i++){
for(int j=1;j<clo;j++){
grid[i][j] = Math.min(grid[i][j-1]+grid[i][j], grid[i-1][j]+grid[i][j]);
}
}
return grid[row-1][clo-1];
}
}
//5ms beat 85.85%
//class Solution {
// public int minPathSum(int[][] grid) {
// if(grid==null || grid.length==0){
// return 0;
// }
//
// int row = grid.length;
// int clo = grid[0].length;
//
// //dp[x][y] 代表从(0,0)到(x,y)的最短距离
// int[][] dp = new int[row][clo];
// dp[0][0] = grid[0][0];
//
// //初始化第一列
// for(int i=1;i<row;i++){
// dp[i][0] = dp[i-1][0] + grid[i][0];
// }
//
// //初始化第一行
// for(int j=1;j<clo;j++){
// dp[0][j] = dp[0][j-1] + grid[0][j];
// }
//
// //计算
// for(int i=1;i<row;i++){
// for(int j=1;j<clo;j++){
// dp[i][j] = Math.min(dp[i][j-1]+grid[i][j], dp[i-1][j]+grid[i][j]);
// }
// }
//
// return dp[row-1][clo-1];
// }
//}