-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum-Falling-Path-Sum-II.java
More file actions
35 lines (31 loc) · 956 Bytes
/
Minimum-Falling-Path-Sum-II.java
File metadata and controls
35 lines (31 loc) · 956 Bytes
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
class Solution {
int N;
public int minFallingPathSum(int[][] grid) {
N = grid.length;
int[][] dp = new int[N][N];
for(int i = 0; i < N; i++){
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
int minVal = Integer.MAX_VALUE;
for(int col = 0; col < N; col++){
minVal = Math.min(minVal, minSum(grid, 0, col, dp));
}
return minVal;
}
public int minSum(int[][] grid, int row, int col, int[][] dp){
if(row == N - 1){
return dp[row][col] = grid[row][col];
}
if(dp[row][col] != Integer.MAX_VALUE){
return dp[row][col];
}
int minVal = Integer.MAX_VALUE;
// Traverse all
for(int j = 0; j < N; j++){
if(j != col){
minVal = Math.min(minVal, minSum(grid, row + 1, j, dp));
}
}
return dp[row][col] = (grid[row][col] + minVal);
}
}