#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 310, INF = 1e9;
PII dir[8] = {{0, 1}, {-1, 1}, {-1, 0}, {-1, -1},
{0, -1}, {1, -1}, {1, 0}, {1, 1}};
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n, m;
char g[N][N];
int d[N][N];
queue<PII> q;
int sx, sy;
bool st[N][N];
void bfs()
{
//memset(d, INF, sizeof d);
queue<PII> q;
q.push({sx, sy});
d[sx][sy] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
if(g[t.x][t.y] == '=')
{
cout << d[t.x][t.y];
return ;
}
// if(g[t.x][t.y] >= 'A' && g[t.x][t.y] <= 'Z')
// {
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<m;j++)
// {
// if(g[i][j]==g[t.x][t.y]&&(i!=t.x|j!=t.y))//如果a[i][j]这个点的是一个与a[nx][ny]相同的传送门,并且a[i][j]与a[nx][ny]不是同一个点
// {
// t.x=i;//改变当前坐标,将贝西强行移动至另一个传送门处
// t.y=j;
// }
// }
// }
// }
for(int i = 0; i < 4; i ++)
{
int x = t.x + dx[i], y = t.y + dy[i];
if(x >= 0 && x < n && y >= 0 && y < n && g[x][y] != '#' && !st[x][y])
{
if(g[x][y] >= 'A' && g[x][y] <= 'Z')
{
for(int j = 0; j < n; j ++)
{
for(int k = 0; k < m; k ++)
{
if(g[j][k] == g[x][y] && (j != x || k != y))
{
d[j][k] = d[t.x][t.y] + 1;
q.push({j, k});
st[x][y] = true;;
}
}
}
}
else
{
d[x][y] = d[t.x][t.y] + 1;
q.push({x, y});
st[x][y] = true;
}
// d[x][y] = d[t.x][t.y] + 1;
// q.push({x, y});
// st[x][y] = true;
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < m; j ++)
{
cin >> g[i][j];
if(g[i][j] == '@')
{
sx = i;
sy = j;
}
}
}
bfs();
return 0;
}