forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add Minimum Path Cost LeetCode problem (TheAlgorithms#1144)
- Loading branch information
1 parent
7aba094
commit 99f06e9
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |