1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { int m, n; int[][] grid; int[][] moveCost; int[][] cache;
public int minPathCost(int[][] grid, int[][] moveCost) { m = grid.length; n = grid[0].length; this.grid = grid; this.moveCost = moveCost; cache = new int[m][n]; int ans = Integer.MAX_VALUE; for (int j = 0; j < n; ++j) { ans = Math.min(ans, dfs(0, j)); } return ans; }
private int dfs(int i, int j) { if (i == m - 1) return grid[i][j]; if (cache[i][j] != 0) return cache[i][j]; int ans = Integer.MAX_VALUE; for (int k = 0; k < n; ++k) { ans = Math.min(ans, dfs(i + 1, k) + moveCost[grid[i][j]][k]); } return cache[i][j] = ans + grid[i][j]; } }
|