Last active
June 23, 2022 20:41
-
-
Save shixiaoyu/d7b9387179f54ec3f8020bfe44efd5f9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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