//gm  --- akezhon
#include <bits/stdc++.h>
// #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define pb push_back
#define pf push_front
#define F first
#define S second
#define all(v) v.begin(),v.end()
#define pii pair<int,int>
#define tm (tl+tr)/2
#define TL v+v, tl, tm
#define TR v+v+1, tm+1, tr
#define DA l <= tl && tr <= r
#define NE r < tl || tr < l
#define double long double
#define int long long 
using namespace std;
const int N=1e5+7;
const int mod=998244353;
const int inf=2e18;
void AlemAmenov(){
	int n, m;
    cin >> n >> m;
    int a[n+2][m+2], dp[n+2][m+2];
    for(int i=1; i <= n; i++){
        for(int j=1; j <= m; j++){
            cin >> a[i][j];
        }
    }
    int ans=-inf;
    for(int i=1; i <= n; i++){
        for(int j=1; j <= m; j++){
            dp[i][j] = -a[i][j]-i-j;
            if(1<i)dp[i][j]=max(dp[i][j],dp[i-1][j]);
            if(1<j)dp[i][j]=max(dp[i][j],dp[i][j-1]);
            ans = max(ans, a[i][j]+i+j + dp[i][j]);
        }
    }
    for(int i=1; i <= n; i++){
        for(int j=m; j >= 1; j--){
            dp[i][j] = -a[i][j]-i+j;
            if(1<i)dp[i][j]=max(dp[i][j], dp[i-1][j]);
            if(j<m)dp[i][j]=max(dp[i][j], dp[i][j+1]);
            ans = max(ans, a[i][j]+i-j + dp[i][j]);
        }
    }
    for(int i=n; i >= 1; i--){
        for(int j=1; j <= m; j++){
            dp[i][j] = -a[i][j]+i-j;
            if(i<n)dp[i][j]=max(dp[i][j], dp[i+1][j]);
            if(1<j)dp[i][j]=max(dp[i][j], dp[i][j-1]);
            ans = max(ans, a[i][j]-i+j + dp[i][j]);
        }
    }
    for(int i=n; i >= 1; i--){
        for(int j=m; j >= 1; j--){
            dp[i][j] = -a[i][j]+i+j;
            if(i<n)dp[i][j]=max(dp[i][j], dp[i+1][j]);
            if(j<m)dp[i][j]=max(dp[i][j], dp[i][j+1]);
            ans = max(ans, a[i][j]-i-j + dp[i][j]);
        }
    }
    cout << ans;
}
signed main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int RealName=1;
    cin >> RealName;
    // freopen("connect.in", "r", stdin);
    // freopen("connect.out", "w", stdout);
    while(RealName--)
        AlemAmenov();
    
return 0;
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |