#include <bits/stdc++.h>
using namespace std;
int n,m;
int quanzhi[100][100];
int bestqz=0;
void dfs(int p,int q,int g)//g作为动态记录最优解的方式,不同于回溯法
{
if(p>n||q>m)
{
return ;
}
if(p==n&&q==m)
{
if(g>bestqz)
bestqz=g;
return ;
}//到达终点之后要写return ;
else
{
for(int t=1;t<=3;t++)
{
dfs(p,q+t,g+quanzhi[p][q+t]);
dfs(p+t,q,g+quanzhi[p+t][q]);
}
dfs(p+1,q+2,g+quanzhi[p+1][q+2]);
dfs(p+2,q+1,g+quanzhi[p+2][q+1]);
dfs(p+2,q+2,g+quanzhi[p+2][q+2]);
}
}
int main()
{
int i,j;
cin>>n>>m;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>quanzhi[i][j];
}//构建地图
dfs(1,1,quanzhi[1][1]);
cout<<bestqz;
return 0;
}
总的来说,把最优解放在dfs函数里记录
见题“蓝桥杯第二页跳跃”