Skip to content

Commit 184c152

Browse files
committed
Leetcode 931 Minimum Falling Path Sum
1 parent fb572a3 commit 184c152

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed
Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,19 @@
11
class Solution {
22
public int minFallingPathSum(int[][] matrix) {
3-
int m = matrix.length;
4-
int n = matrix[0].length;
5-
6-
for(int i=m-2;i>=0;i--)
7-
{
8-
for(int j=0;j<n;j++)
9-
{
10-
if(j == 0) {
11-
matrix[i][j] += Math.min(matrix[i+1][j], matrix[i+1][j+1]);
12-
}else if(j == n-1) {
13-
matrix[i][j] += Math.min(matrix[i+1][j-1], matrix[i+1][j]);
14-
}else{
15-
matrix[i][j] += Math.min(matrix[i+1][j-1], Math.min(matrix[i+1][j], matrix[i+1][j+1]));
16-
}
3+
int m = matrix.length, n = matrix[0].length;
4+
for(int row=1;row<m;row++) {
5+
for(int col=0;col<n;col++) {
6+
int leftTop = col == 0 ? Integer.MAX_VALUE : matrix[row-1][col-1];
7+
int top = matrix[row-1][col];
8+
int rightTop = col == n-1 ? Integer.MAX_VALUE : matrix[row-1][col+1];
9+
matrix[row][col] += ( Math.min(leftTop, Math.min(top, rightTop)));
1710
}
1811
}
19-
20-
int ans = matrix[0][0];
21-
22-
for(int i=1;i<n;i++)
23-
ans = Math.min(ans, matrix[0][i]);
24-
12+
13+
int ans = Integer.MAX_VALUE;
14+
for(int i=0;i<n;i++) {
15+
ans = Math.min(ans, matrix[m-1][i]);
16+
}
2517
return ans;
2618
}
2719
}

0 commit comments

Comments
 (0)