feat: add Minimum Path Cost LeetCode problem (#1144)

This commit is contained in:
Alexander Pantyukhin 2022-11-25 09:14:53 +04:00 committed by GitHub
parent 7aba094afb
commit 99f06e97e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 0 deletions

View File

@ -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 | | 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 | | 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 | | 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
View 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;
}