首先按红线所示方向走即 dp[i-1][j] 和dp[i][j-1] ,然后按黄线所示方向 dp[i-1][j] 和dp[i][j+1],这样即可遍历所有情况
#include <bits/stdc++.h>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
#define int long long int
#define endl '\n'
typedef pair<int, int> PII;
const int mod = 998244353;
const int inf = 0x3f3f3f3f;
const int N = 1e3 + 7;
int a[N][N];
int dp[N][N], f[N][N];
signed main() {
int n, m, c;
cin >> n >> m >> c;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
mem(dp, inf);
int ans = 1e18;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = min({dp[i][j - 1] + c, dp[i - 1][j] + c, a[i][j]});
f[i][j] = min(dp[i - 1][j] + c + a[i][j], dp[i][j - 1] + c + a[i][j]);
ans = min(ans, f[i][j]);
}
}
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
dp[i][j] = min({dp[i][j + 1] + c, dp[i - 1][j] + c, a[i][j]});
f[i][j] = min(dp[i - 1][j] + c + a[i][j], dp[i][j + 1] + c + a[i][j]);
ans = min(ans, f[i][j]);
}
}
cout << ans << endl;
return 0;
}