由于他每一行的每一个值都可以到下一行的所有节点,且路径的代价没有什么相关性,所以只能用 O(mn2) 的动态规划求解
class Solution:def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:m, n = len(grid), len(grid[0])dp = [[inf] * n for _ in range(m)]dp[0] = [i for i in grid[0]]for i in range(1, m):for j in range(n):for k in range(n):dp[i][j] = min(dp[i][j], grid[i][j] + dp[i - 1][k] + moveCost[grid[i - 1][k]][j])return min(dp[m - 1])