#include<iostream>
#include<queue>
using namespace std;
int step[400][400];
queue<pair<int,int>>c;
char a[400][400];
bool vis[400][400];
int n, m;
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int sx,sy;
void change(int &x, int &y) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (a[i][j] == a[x][y] && (i != x || j != y)) {
x = i;
y = j;
return;
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cin >> a[i][j];
if (a[i][j] == '@') {
sx = i;
sy = j;
}
}
}
c.push({sx, sy});
vis[sx][sy] = true;
step[sx][sy]=0;
while (!c.empty()) {
int dx=c.front().first;
int dy=c.front().second;
c.pop();
if (a[dx][dy] == '=') {
cout << step[dx][dy] << endl;
return 0;
}
if (a[dx][dy] >= 'A' && a[dx][dy] <= 'Z') {
change(dx, dy);
}
for (int i = 0; i < 4; ++i) {
int nx = dx + d[i][0];
int ny = dy + d[i][1];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && a[nx][ny] != '#' && !vis[nx][ny]) {
vis[nx][ny] = true;
c.push({nx,ny});
step[nx][ny]=step[dx][dy]+1;
}
}
}
return 0;
}