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
| class Solution {
int[][] matrix; int[][] cache;
public int minFallingPathSum(int[][] matrix) { int n = matrix.length, ans = Integer.MAX_VALUE; this.matrix = matrix; cache = new int[n][n]; for (int i = 0; i < n; ++i) { Arrays.fill(cache[i], Integer.MIN_VALUE); }
for (int col = 0; col < n; ++col) { ans = Math.min(ans, dfs(n - 1, col)); } return ans; }
private int dfs(int row, int col) { if (col < 0 || col >= matrix.length) return Integer.MAX_VALUE; if (row == 0) return matrix[0][col]; if (cache[row][col] != Integer.MIN_VALUE) return cache[row][col]; return cache[row][col] = Math.min(Math.min(dfs(row - 1, col - 1), dfs(row - 1, col)), dfs(row - 1, col + 1)) + matrix[row][col]; } }
|