自己看吧
#include<bits/stdc++.h>
using namespace std;
long long a,s,d[9][9],j,k,l,max1,u,i,y;
bool f[8][8];
bool w(int v,int b){
return !(f[v-1][b-1]||f[v-1][b]||f[v-1][b+1]||f[v][b-1]||f[v][b]||f[v][b+1]||f[v+1][b-1]||f[v+1][b]||f[v+1][b+1]);
}
int q(int z,int x){
l+=d[z][x];
f[z][x]=1;
if(l>=max1){
max1=l;
}
for(int g=1;g<=a;g++){
for(int h=1;h<=s;h++){
if(w(g,h)) q(g,h);
}
}
l-=d[z][x];
f[z][x]=0;
return 0;
}
int main(){
cin>>y;
for(int p=0;p<y;p++){
max1=0;
l=0;
cin>>a>>s;
for(j=0;j<=a+1;j++){
for(k=0;k<a+2;k++){
f[j][k]=0;
}
}
for(j=1;j<=a;j++){
for(k=1;k<=s;k++){
cin>>d[j][k];
}
}
for(j=1;j<=a;j++){
for(k=1;k<=s;k++){
q(j,k);
}
}
cout<<max1<<'\n';
}
}