Skip to content

Commit 8aea1ba

Browse files
Create 0931-minimum-falling-path-sum.java
1 parent df1a58a commit 8aea1ba

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*----------------------------------
2+
Time Complexity: O(n^2)
3+
Space Complexity: (1)
4+
----------------------------------*/
5+
6+
class Solution {
7+
public int minFallingPathSum(int[][] matrix) {
8+
int N = matrix.length;
9+
10+
for(int r = 1; r < N; r++){
11+
for(int c = 0; c < N; c++){
12+
int mid = matrix[r-1][c];
13+
int left = (c > 0)? matrix[r-1][c-1]: Integer.MAX_VALUE;
14+
int right = (c < N-1)? matrix[r-1][c+1]: Integer.MAX_VALUE;
15+
matrix[r][c] = matrix[r][c] + Math.min(left, Math.min(mid, right));
16+
}
17+
}
18+
int res = Integer.MAX_VALUE;
19+
for(int i = 0; i < N; i++){
20+
res = Math.min(res, matrix[N-1][i]);
21+
}
22+
return res;
23+
}
24+
}
25+
26+
/*----------------------------------
27+
Time Complexity: O(n^2)
28+
Space Complexity: (n^2)
29+
----------------------------------*/
30+
31+
class Solution {
32+
public int minFallingPathSum(int[][] matrix) {
33+
int n = matrix.length;
34+
int[][] dp = new int[n+1][n+1];
35+
36+
for(int i = n-1; i >= 0; i--){
37+
for(int j = 0; j < n; j++){
38+
if(j == 0)
39+
dp[i][j] = matrix[i][j] + Math.min(dp[i+1][j], dp[i+1][j+1]);
40+
else if (j == n-1) {
41+
dp[i][j] = matrix[i][j] + Math.min(dp[i+1][j-1], dp[i+1][j]);
42+
} else{
43+
int min = dp[i+1][j-1];
44+
if(dp[i+1][j] < min)
45+
min = dp[i+1][j];
46+
if(dp[i+1][j+1] < min)
47+
min = dp[i+1][j+1];
48+
49+
dp[i][j] = matrix[i][j] + min;
50+
}
51+
}
52+
}
53+
int res = Integer.MAX_VALUE;
54+
for(int i=0; i<n; i++)
55+
res = Math.min(res, dp[0][i]);
56+
57+
return res;
58+
}
59+
}

0 commit comments

Comments
 (0)