|
| 1 | +package javacode.solutions; |
| 2 | + |
| 3 | +// [Problem] https://leetcode.com/problems/minimum-falling-path-sum |
| 4 | +class MinimumFallingPathSum { |
| 5 | + // Dynamic programming |
| 6 | + // O(m * n) time, O(1) space |
| 7 | + // where m = row size, n = column size |
| 8 | + public int minFallingPathSum(int[][] matrix) { |
| 9 | + int rowSize = matrix.length, colSize = matrix[0].length; |
| 10 | + int totalMinSum = Integer.MAX_VALUE; |
| 11 | + for (int row = 0; row < rowSize; row++) { |
| 12 | + for (int col = 0; col < colSize; col++) { |
| 13 | + if (row >= 1) { |
| 14 | + int minSum = matrix[row][col]; |
| 15 | + if (colSize == 1) { |
| 16 | + minSum += matrix[row - 1][col]; |
| 17 | + } else if (col == 0) { |
| 18 | + minSum += Math.min(matrix[row - 1][col], matrix [row - 1][col + 1]); |
| 19 | + } else if (col == colSize - 1) { |
| 20 | + minSum += Math.min(matrix[row - 1][col], matrix [row - 1][col - 1]); |
| 21 | + } else { |
| 22 | + minSum += Math.min(matrix[row - 1][col], Math.min(matrix[row - 1][col - 1], matrix [row - 1][col + 1])); |
| 23 | + } |
| 24 | + matrix[row][col] = minSum; |
| 25 | + } |
| 26 | + if (row == rowSize - 1) { |
| 27 | + totalMinSum = Math.min(matrix[row][col], totalMinSum); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + return totalMinSum; |
| 32 | + } |
| 33 | + |
| 34 | + // Test |
| 35 | + public static void main(String[] args) { |
| 36 | + MinimumFallingPathSum solution = new MinimumFallingPathSum(); |
| 37 | + |
| 38 | + int[][] input = { |
| 39 | + {2, 1, 3}, |
| 40 | + {6, 5, 4}, |
| 41 | + {7, 8, 9} |
| 42 | + }; |
| 43 | + int expectedOutput = 13; |
| 44 | + int actualOutput = solution.minFallingPathSum(input); |
| 45 | + |
| 46 | + System.out.println("Test passed? " + (expectedOutput == actualOutput)); |
| 47 | + } |
| 48 | +} |
0 commit comments