cpp:
#include <iostream>
#include <vector>
#include <ctype.h>
#define PII pair<int,int>
#define fir first
#define sec second
using namespace std;
const int N = 310;
int n, m, s, e, ss, ee, res;
char g[N][N];
int vis[N][N];
vector<pair<PII, char>> v;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
inline pair<PII, int> find(int x, int y) {
char s = ' ';
for (auto i : v) {
auto xx = i.fir.fir, yy = i.fir.sec, c = i.fir.sec;
if (xx == x && yy == y) {
s = c;
} else if (c == s) {
return {{xx, yy}, 1};
}
}
return {{0, 0}, 0};
}
inline void dfs(int x, int y, int step) {
if (step > res) {
return ;
}
if (x == ss && y == ee) {
res = step;
return ;
}
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx >= 1 && yy >= 1 && xx <= n && yy <= m && g[xx][yy] != '#') {
auto t = find(xx, yy);
if (t.sec) {
dfs(t.fir.fir, t.fir.sec, step);
}
dfs(xx, yy, step + 1);
}
}
return ;
}
signed main() {
ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> g[i][j];
if (g[i][j] == '@') {
s = i, e = j;
} else if (g[i][j] == '=') {
ss = i, ee = j;
} else if (g[i][j] >= 'A' && g[i][j] <= 'Z') {
v.push_back({{i, j}, g[i][j]});
}
}
}
dfs(s, e, 0);
cout << res << '\n';
return 0;
}