From 99f06e97e761b9048951e5cc7c5970e2fbf83c81 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Fri, 25 Nov 2022 09:14:53 +0400 Subject: [PATCH] feat: add Minimum Path Cost LeetCode problem (#1144) --- leetcode/DIRECTORY.md | 1 + leetcode/src/2304.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 leetcode/src/2304.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 040d5b8d..a79c1aff 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -100,3 +100,4 @@ | 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium | | 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy | | 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium | +| 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | diff --git a/leetcode/src/2304.c b/leetcode/src/2304.c new file mode 100644 index 00000000..d8cfcb25 --- /dev/null +++ b/leetcode/src/2304.c @@ -0,0 +1,42 @@ +#define min(x,y)(((x)<(y))?(x):(y)) + +// DP up -> down. We are going down from gridline to gridline +// and collect the minumum cost path. +// Runtime : O(gridSize*gridColSize*gridColSize) +// Space: O(gridColSize) +int minPathCost(int** grid, int gridSize, int* gridColSize, int** moveCost, int moveCostSize, int* moveCostColSize){ + int* dp = (int*)calloc(gridColSize[0], sizeof(int)); + int* newDp = (int*)calloc(gridColSize[0], sizeof(int)); + + for(int i = 0; i < gridSize - 1; i++){ + int currGridColSize = gridColSize[i]; + for(int j = 0; j < currGridColSize; j++){ + newDp[j] = -1; + } + + for(int j = 0; j < currGridColSize; j++){ + int currGridItem = grid[i][j]; + for(int z = 0; z < currGridColSize; z++){ + int currMoveCost = dp[j] + moveCost[currGridItem][z] + currGridItem; + + newDp[z] = (newDp[z] == -1) ? currMoveCost : min(newDp[z], currMoveCost); + } + } + + for(int j = 0; j < currGridColSize; j++){ + dp[j] = newDp[j]; + } + } + + // Find minimum value. + int minValue = dp[0] + grid[gridSize - 1][0]; + for(int j = 1; j < gridColSize[0]; j++){ + minValue = min(minValue, dp[j] + grid[gridSize - 1][j]); + } + + // free resources + free(dp); + free(newDp); + + return minValue; +}