Skip to content

Commit

Permalink
feat: add Minimum Path Cost LeetCode problem (TheAlgorithms#1144)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpantyukhin authored Nov 25, 2022
1 parent 7aba094 commit 99f06e9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions leetcode/DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
42 changes: 42 additions & 0 deletions leetcode/src/2304.c
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit 99f06e9

Please sign in to comment.