mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
feat: add Minimum Path Cost LeetCode problem (#1144)
This commit is contained in:
parent
7aba094afb
commit
99f06e97e7
@ -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
leetcode/src/2304.c
Normal file
42
leetcode/src/2304.c
Normal file
@ -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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user