// Code language: C++ classSolution { public: intminPathCost(vector<vector<int>>& grid, vector<vector<int>>& moveCost){ int n = grid.size(), m = grid[0].size(); vector<vector<int>> dp(2, vector<int>(m)); for (int i = 0; i < m; i++) dp[0][i] = grid[0][i]; for (int i = 1; i < n; i++) { for (int j = 0; j < m; j++) { dp[i % 2][j] = INT_MAX; for (int k = 0; k < m; k++) { dp[i % 2][j] = min(dp[i % 2][j], dp[(i - 1) % 2][k] + moveCost[grid[i - 1][k]][j]); } dp[i % 2][j] += grid[i][j]; } } int ans = INT_MAX; for (int i = 0; i < m; ++i) { ans = min(ans, dp[(n - 1) % 2][i]); } return ans; } };
/* Code language: Go */ funcminPathCost(grid [][]int, moveCost [][]int)int { var n, m = len(grid), len(grid[0]) dp := make([][]int, 2) for i := 0; i < 2; i++ { dp[i] = make([]int, m) } for i, j := range grid[0] { dp[0][i] = j } for i := 1; i < n; i++ { for j := 0; j < m; j++ { dp[i % 2][j] = math.MaxInt; for k := 0; k < m; k++ { dp[i % 2][j] = min(dp[i % 2][j], dp[(i - 1) % 2][k] + moveCost[grid[i - 1][k]][j]) } dp[i % 2][j] += grid[i][j] } } ans := math.MaxInt for i := 0; i < m; i++ { ans = min(ans, dp[(n - 1) % 2][i]) } return ans }