From 1b6fe6ea17d2ae0983fcff47c1aec77e2790a994 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Wed, 18 Jan 2023 23:54:30 +0400 Subject: [PATCH] feat: add Minimum Falling Path Sum (#1182) Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/931.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 leetcode/src/931.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 5b38cdf82..8533e8994 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -100,6 +100,7 @@ | 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/) | [C](./src/901.c) | Medium | | 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C](./src/905.c) | Easy | | 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/) | [C](./src/917.c) | Easy | +| 931 | [Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/description/) | [C](./src/931.c) | Medium | | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy | | 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy | diff --git a/leetcode/src/931.c b/leetcode/src/931.c new file mode 100644 index 000000000..b257c8c33 --- /dev/null +++ b/leetcode/src/931.c @@ -0,0 +1,37 @@ +#define min(a,b) (((a)<(b))?(a):(b)) + +// Dynamic programming. +// Runtime O(n*n) +// Space O(n) +int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize){ + int* dp = calloc(matrixSize, sizeof(int)); + + for (int i = 0; i < matrixSize; i++){ + int* nextDp = calloc(matrixSize, sizeof(int)); + + for (int j = 0; j < matrixSize; j++){ + nextDp[j] = dp[j] + matrix[i][j]; + + // If not the first column - try to find minimum in prev column + if(j > 0){ + nextDp[j] = min(nextDp[j], dp[j - 1] + matrix[i][j]); + } + + // If not the last column - try to find minimum in next column + if (j < matrixSize - 1){ + nextDp[j] = min(nextDp[j], dp[j + 1] + matrix[i][j]); + } + } + + free(dp); + dp = nextDp; + } + + int result = dp[0]; + for (int j = 1; j < matrixSize; j++){ + result = min(result, dp[j]); + } + + free(dp); + return result; +}