aboutsummaryrefslogtreecommitdiff
path: root/other/min_path_sum.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/min_path_sum.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/min_path_sum.cpp')
-rw-r--r--other/min_path_sum.cpp29
1 files changed, 29 insertions, 0 deletions
diff --git a/other/min_path_sum.cpp b/other/min_path_sum.cpp
new file mode 100644
index 0000000..46c2ff1
--- /dev/null
+++ b/other/min_path_sum.cpp
@@ -0,0 +1,29 @@
+// 64. Minimum Path Sum
+#include "leetcode.h"
+
+// given 'm x n grid' filled with non-negative numbers, find a path from top
+// left to bottom right, which minimises the sum of all numbers along its path
+
+class Solution {
+public:
+ int minPathSum(vvd & grid) {
+ int m = grid.size(), n = grid[0].size();
+ vvd sum(m, vector<int>(n, grid[0][0]));
+ for (int i = 1; i < m; i++)
+ sum[i][0] = sum[i - 1][0] + grid[i][0];
+ for (int j = 1; j < n; j++)
+ sum[0][j] = sum[0][j - 1] + grid[0][j];
+ for (int i = 1; i < m; i++)
+ for (int j = 1; j < n; j++)
+ sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
+ return sum[m - 1][n - 1];
+ }
+};
+
+int main() {
+ Solution obj;
+ vvd g1 = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
+ vvd g2 = {{1, 2, 3}, {4, 5, 6}};
+ printf("%d\n", obj.minPathSum(g1)); // expect: 7
+ printf("%d\n", obj.minPathSum(g2)); // expect: 12
+}