#include<iostream>
using namespace std;
#include<queue>
struct coord
{
int x, y, step;
};
struct f
{
int x1, y1, x2, y2;
}mark[100];
queue<coord>Q;
int n, m, wk[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
char a[305][305], t;
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> t;
a[i][j] = t;
if (t == '@')
{
a[i][j] = '#';
Q.push({ i,j,0 });
}
else if (isalpha(t))
{
if (mark[t].x1 == 0) mark[t].x1 = i, mark[t].y1 = j;
else mark[t].x2 = i, mark[t].y2 = j;
}
}
}
while (!Q.empty())
{
coord u = Q.front();
Q.pop();
for (int i = 0; i < 4; i++)
{
int x = u.x + wk[i][0], y = u.y + wk[i][1];
if (x < 0 || x >= n || y < 0 || y >= n || a[x][y] == '#') continue;
if (a[x][y] == '.')
{
a[x][y] = '#';
Q.push({ x,y,u.step + 1 });
continue;
}
if (a[x][y] == '=')
{
cout << u.step + 1;
return 0;
}
if (x == mark[a[x][y]].x1 && y == mark[a[x][y]].y1) Q.push({ mark[a[x][y]].x2,mark[a[x][y]].y2,u.step + 1 });
else Q.push({ mark[a[x][y]].x1,mark[a[x][y]].y1,u.step + 1 });
}
}
return 0;
}