931. Minimum Falling Path Sum
DFS + memo
T: O(3^row)
S: O(row*col)
public class Solution {
public int minFallingPathSum(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
Integer[][] memo = new Integer[m][n];
int min = Integer.MAX_VALUE;
// ๅพ row 0 ้ๅง่ทๆๆ row 0 ็ cell, ไพๅไนๅพ็ๅๆฏ
// ๆไปฅๆ 0,0 0,1 0,2 ไธๅ
ฅ dfs function
for (int c = 0; c < n; c++) { // row 0, put all (row, col)
// ๅ ็บๆๅ memo, ๆไปฅ 0,1 0,2 ่ท็ๆๅ, ๅ
ถๅฏฆไธ้ข dfs ็ๅๆฏ้ฝ่จ็ฎ้ไบ
min = Math.min(min, dfs(matrix, 0, c, memo));
}
return min;
}
// dfs function ไพ recursive ่จ็ฎ min path value
private int dfs(int[][] matrix, int row, int col, Integer[][] memo) {
int m = matrix.length;
int n = matrix[0].length;
if (!isValid(m, n, row, col)) {
return 0;
}
if (memo[row][col] != null) {
return memo[row][col];
}
int min = Integer.MAX_VALUE;
for (int i = -1; i <= 1; i++) {
if (!isValid(m, n, row, col+i)) { // why check row..., not row+1 ?
// because row+1 check is in the beginning of dfs? so why need check?
continue;
}
// for every cell (row, col)
// => has 3 branch => (row+1, col-1),(row+1, col), (row+1, col-1)
// sum = ็ฎๅๅผ + 3 ๅๆฏ็ๅผ
int sum = matrix[row][col] + dfs(matrix, row+1, col + i, memo);
min = Math.min(min, sum); // ๅๆๅฐ็
}
memo[row][col] = min; // ็ด้ๆๅฐๅผ
return min;
}
private boolean isValid(int m, int n, int row, int col) {
return row >= 0 && row < m && col >=0 && col < n;
}
}
/*
row. [0,0 0,1 0,2]
/|\
r+1,c-1 c c+1
T: O(3^row)
S: O(mn)
*/DP
top down, because this Q ask from top to end's min path sum
Last updated
Was this helpful?