#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 310;
int n, m;
int end_x, end_y, sta_x, sta_y;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
char g[N][N];
int d[N][N];
int ghuansong[N * N];
int bfs() {
queue<PII> q;
PII t = {sta_x, sta_y};
q.push(t);
while (!q.empty()) {
auto pp = q.front();
q.pop();
if (ghuansong[pp.first * N + pp.second]) {
d[ghuansong[pp.first * N + pp.second] / N][ ghuansong[pp.first * N + pp.second] % N] = d[pp.first][pp.second] + 1;
q.push({ghuansong[pp.first * N + pp.second] / N, ghuansong[pp.first * N + pp.second] % N});
}
if (pp.first == end_x && pp.second == end_y) break;
for (int i = 0; i < 4; i++) {
int x = pp.first + dx[i];
int y = pp.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] ^ '#' && d[x][y] == -1) {
d[x][y] = d[pp.first][pp.second] + 1;
q.push({x, y});
}
}
}
return d[end_x][end_y] - 1;
}
int tmp[128];
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] >= 'A' && g[i][j] <= 'Z') {
if (tmp[g[i][j]]) {
ghuansong[tmp[g[i][j]]] = i * N + j;
ghuansong[i * N + j] = tmp[g[i][j]];
} else tmp[g[i][j]] = i * N + j;
} else if (g[i][j] == '=')end_x = i, end_y = j;
else if (g[i][j] == '@')sta_x = i, sta_y = j;
}
memset(d, -1, sizeof(d));
d[sta_x][sta_y] = 0;
cout << bfs() << endl;
return 0;
}