推荐DFS
#include <iostream>
using namespace std;
const int N = 30;
char graph[N][N];
bool vis[N][N];
bool letter[26];
int n, m;
int res;
int dic[4][2] = {
{0, -1}, {-1, 0}, {0, 1}, {1, 0}
};
bool check(int x, int y){
if(x >= 0 && x < n && y >= 0 && y < m) return true;
return false;
}
void dfs(int x, int y, int cnt){
if(cnt > res) res = cnt;
for(int i = 0; i < 4; i ++ ){
int xx = x + dic[i][0], yy = y + dic[i][1];
if(check(xx, yy) && !vis[xx][yy] && !letter[graph[xx][yy] - 'A']){
vis[xx][yy] = true;
letter[graph[xx][yy] - 'A'] = true;
dfs(xx, yy, cnt + 1);
letter[graph[xx][yy] - 'A'] = false;
vis[xx][yy] = false;
}
}
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i ++ ) cin >> graph[i];
letter[graph[0][0] - 'A'] = true;
dfs(0, 0, 1);
cout << res << endl;
return 0;
}
BFS
#include <iostream>
#include <queue>
#include <unordered_map>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
const int N = 25;
char graph[N][N];
int n, m;
struct node{
pii loc;
bool flag[26];
int cnt;
};
int dic[4][2] = {
{0, -1}, {-1, 0}, {0, 1}, {1, 0}
};
bool check(int x, int y){
if(x >= 0 && x < n && y >= 0 && y < m) return true;
return false;
}
int res;
void bfs(){
queue<node> qu;
node st;
st.loc = {0, 0}, st.flag[graph[0][0] - 'A'] = true;
st.cnt = 1;
qu.push(st);
while(!qu.empty()){
node now = qu.front();
qu.pop();
res = max(res, now.cnt);
for(int i = 0; i < 4; i ++ ){
int xx = now.loc.first + dic[i][0];
int yy = now.loc.second + dic[i][1];
if(check(xx, yy) && !now.flag[graph[xx][yy] - 'A']){
node nxt;
nxt.loc = {xx, yy}, nxt.cnt = now.cnt;
memcpy(nxt.flag, now.flag, sizeof now.flag);
nxt.cnt ++ ;
nxt.flag[graph[xx][yy] - 'A'] = true;
qu.push(nxt);
}
}
}
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i ++ ) cin >> graph[i];
bfs();
cout << res << endl;
return 0;
}