From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/min_falling_path_sum.cpp | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 other/min_falling_path_sum.cpp (limited to 'other/min_falling_path_sum.cpp') diff --git a/other/min_falling_path_sum.cpp b/other/min_falling_path_sum.cpp new file mode 100644 index 0000000..3bc2940 --- /dev/null +++ b/other/min_falling_path_sum.cpp @@ -0,0 +1,45 @@ +#include "leetcode.h" + +/* + * given NxN array of integers 'matrix' return the minimum + * sum of any falling path through 'matrix' + * + * a falling path starts at any element in row 0 and chooses + * the element in the next row that is either directly below + * or diagonally left/right that obviously makes for the lowest sum + */ + +class Solution { +public: + int minFallingPathSum(vvd & matrix) { + vvd dp(matrix.size(), vector(matrix.size(), INT_MAX)); + for (int i = 0; i < matrix.size(); i++) + dp[0][i] = matrix[0][i]; + for (int i = 1; i < matrix.size(); i++) { + for (int j = 0; j < matrix.size(); j++) { + if (j > 0 && j < matrix.size() - 1) { + dp[i][j] = + min(dp[i - 1][j - 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]); + dp[i][j] = min(dp[i - 1][i + 1] + matrix[i][j], dp[i][j]); + } else if (j == 0) + dp[i][j] = + min(dp[i - 1][j + 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]); + else if (j == matrix.size() - 1) + dp[i][j] = + min(dp[i - 1][j - 1] + matrix[i][j], dp[i - 1][j] + matrix[i][j]); + } + } + int ans = INT_MAX; + for (auto &x : dp[dp.size() - 1]) + ans = min(ans, x); + return ans; + } +}; + +int main() { + Solution obj; + vvd matrix = {{2, 1, 3}, // 1 + {6, 5, 4}, //-> 4 + {7, 8, 9}}; // 8 <- + cout << obj.minFallingPathSum(matrix); // expect 13 +} -- cgit v1.2.3