#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <bitset>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <map>
#include <set>
#include<iomanip>
#include <bits/stdc++.h>
/***************************************/
#define ll long long
#define int64 __int64
#define PI 3.1415927
#define INF 1000000
const int maxn = 10010;
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
#include <bits/stdc++.h>
using namespace std;
int r,s;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
struct node
{
int x,y;int step;
} ;
char mp[25][25];
int vis[27];
int vismap[25][25];
int ans;
void dfs(node a )
{
ans=max(ans,a.step);
//判断四个方向
for(int i=0;i<4;i++)
{
node nx;
nx.x=a.x+dx[i];
nx.y=a.y+dy[i];
if((nx.x<r)&&(nx.x>=0)&&nx.y>=0&&nx.y<s&&vis[mp[nx.x][nx.y]-'A']==0&&vismap[nx.x][nx.y]==0)
{
nx.step=a.step+1;
vis[mp[nx.x][nx.y]-'A']=1;
vismap[nx.x][nx.y]=1;
dfs(nx );
// cout<<nx.x<<" "<<nx.y<<" "<<mp[nx.x][nx.y]<<" "<<nx.step<<endl;
nx.step--;
vismap[nx.x][nx.y]=0;
vis[mp[nx.x][nx.y]-'A']=0;
}
}
}
int main()
{
cin>>r>>s;
memset(vis,0,sizeof(vis));
memset(vismap,0,sizeof(vismap));
ans=-1;
for(int i=0;i<r;i++)
for(int j=0;j<s;j++)
{
cin>>mp[i][j];
}
vismap[0][0]=1;
vis[mp[0][0]-'A']=1;
node st;
st.x=0;
st.y=0;
st.step=1;
dfs(st );
cout<<ans;
return 0;
}
dfs基础题 注意dfs往回倒 紫书上说这块新手上路会卡几天几个月甚至一年。。。。 要是理解不了就背写书上的代码