|
| 1 | +/** |
| 2 | + * Implementation of the Minimum Falling Path Sum problem using Dynamic |
| 3 | + * Programming. |
| 4 | + * |
| 5 | + * Given an n x n integer matrix, the algorithm finds the minimum sum of any |
| 6 | + * falling path through the matrix. A falling path starts at any element in the |
| 7 | + * first row and chooses one element from each row below, such that the next |
| 8 | + * element is in the same column or an adjacent column. |
| 9 | + * |
| 10 | + * <p>Example: |
| 11 | + * Input: |
| 12 | + * 3 |
| 13 | + * 2 1 3 |
| 14 | + * 6 5 4 |
| 15 | + * 7 8 9 |
| 16 | + * |
| 17 | + * Output: |
| 18 | + * 13 |
| 19 | + * |
| 20 | + * <p>Approach: Bottom-up Dynamic Programming |
| 21 | + * Time Complexity: O(n^2) |
| 22 | + * Space Complexity: O(n^2) |
| 23 | + * |
| 24 | + * @see <a |
| 25 | + * href="https://leetcode.com/problems/minimum-falling-path-sum/">LeetCode: |
| 26 | + * Minimum Falling Path Sum</a> |
| 27 | + * @see <a href="https://en.wikipedia.org/wiki/Dynamic_programming">Wikipedia: |
| 28 | + * Dynamic Programming</a> |
| 29 | + */ |
| 30 | + |
| 31 | +package dp; |
| 32 | + |
| 33 | +import java.util.*; |
| 34 | + |
| 35 | +public class MinFallingPathSum { |
| 36 | + |
| 37 | + public static int minFallingPathSum(int[][] matrix) { |
| 38 | + int n = matrix.length; |
| 39 | + int[][] dp = new int[n][n]; |
| 40 | + for (int i = 0; i < n; i++) |
| 41 | + dp[n - 1][i] = matrix[n - 1][i]; |
| 42 | + for (int i = n - 2; i >= 0; i--) { |
| 43 | + for (int j = 0; j < n; j++) { |
| 44 | + int downLeft = |
| 45 | + (i + 1 < n && j - 1 >= 0) ? dp[i + 1][j - 1] : Integer.MAX_VALUE; |
| 46 | + int downRight = |
| 47 | + (i + 1 < n && j + 1 < n) ? dp[i + 1][j + 1] : Integer.MAX_VALUE; |
| 48 | + int down = (i + 1 < n) ? dp[i + 1][j] : Integer.MAX_VALUE; |
| 49 | + dp[i][j] = matrix[i][j] + Math.min(down, Math.min(downLeft, downRight)); |
| 50 | + } |
| 51 | + } |
| 52 | + int mini = Integer.MAX_VALUE; |
| 53 | + for (int i = 0; i < n; i++) |
| 54 | + mini = Math.min(mini, dp[0][i]); |
| 55 | + return mini; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) { |
| 59 | + Scanner sc = new Scanner(System.in); |
| 60 | + int n = sc.nextInt(); |
| 61 | + int[][] matrix = new int[n][n]; |
| 62 | + for (int i = 0; i < n; i++) |
| 63 | + for (int j = 0; j < n; j++) |
| 64 | + matrix[i][j] = sc.nextInt(); |
| 65 | + System.out.println(minFallingPathSum(matrix)); |
| 66 | + } |
| 67 | +} |
0 commit comments