Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Last active June 23, 2022 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shixiaoyu/d7b9387179f54ec3f8020bfe44efd5f9 to your computer and use it in GitHub Desktop.
Save shixiaoyu/d7b9387179f54ec3f8020bfe44efd5f9 to your computer and use it in GitHub Desktop.
public int minPathCost(int[][] grid, int[][] moveCost) {
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0 || moveCost == null) {
return -1; // or throw exception
}
int[][] minCost = new int[grid.length][grid[0].length];
for (int i = 0; i < minCost[0].length; i++) {
minCost[0][i] = grid[0][i]; // first row costs are the init values
}
for (int i = 1; i < minCost.length; i++) {
for (int j = 0; j < minCost[0].length; j++) {
int min = Integer.MAX_VALUE;
for (int k = 0; k < minCost[0].length; k++) {
min = Math.min(min, minCost[i - 1][k] + moveCost[grid[i - 1][k]][j]);
}
minCost[i][j] = grid[i][j] + min;
}
}
int finalMin = Integer.MAX_VALUE;
for (int i = 0; i < minCost[0].length; i++) {
finalMin = Math.min(minCost[minCost.length - 1][i], finalMin);
}
return finalMin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment