dfs
C++ 代码
#include <iostream>
#include <unordered_set>
using namespace std;
const int N = 22;
char d[N][N];
int n, m, ret = 0;
unordered_set<char> mm;
int dxy[] = { 0, 1, 0, -1, 0 };
void dfs(int x, int y)
{
ret = max(ret, (int)mm.size());
for(int i = 0; i < 4; ++ i){
int nx = x + dxy[i], ny = y + dxy[i + 1];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && mm.count(d[nx][ny]) == 0)
{
mm.insert(d[nx][ny]);
dfs(nx, ny);
mm.erase(d[nx][ny]);
}
}
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; ++ i)
for(int j = 0; j < m; ++ j)
cin >> d[i][j];
mm.insert(d[0][0]);
dfs(0, 0);
cout << ret << endl;
return 0;
}