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 30 31 32 33 34 35
| func minPathCost(grid [][]int, moveCost [][]int) int { m := len(grid) n := len(grid[0]) ans := math.MaxInt visits := make([][]int, m) for i := 0; i < m; i++ { visits[i] = make([]int, n) } for i := 0; i < n; i++ { ans = min(ans, dfs(grid, moveCost, visits, 0, i, m, n)) } return ans }
func dfs(grid [][]int, moveCost [][]int, visits [][]int, i, j, m, n int) int { if visits[i][j] != 0 { return visits[i][j] } if i == m - 1 { return grid[i][j] } minVal := math.MaxInt for k := 0; k < n; k++ { minVal = min(minVal, dfs(grid, moveCost, visits, i + 1, k, m, n) + moveCost[grid[i][j]][k]) } visits[i][j] = grid[i][j] + minVal return visits[i][j] }
func min(num1, num2 int) int { if num1 <= num2 { return num1 } return num2 }
|