#include<bits/stdc++.h>
using namespace std;
int n, m, a, b, c, d;
char g[305][305];
typedef pair<int, int>PII;
queue<PII>q;
int dist[305][305];
int st[305][305];
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
int bfs(int x, int y) {
dist[x][y] = 0;
q.push({ x,y });
st[x][y] = 1;
while (q.size()) {
auto t = q.front();
q.pop();
if (g[t.first][t.second] >= 'A' && g[t.first][t.second] <= 'Z') {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i == t.first && t.second == j) continue;
if (g[t.first][t.second] == g[i][j]) {
t.first = i;
t.second = j;
break;
}
}
}
}
for (int i = 0; i < 4; i++) {
int e = t.first + dx[i];
int f = t.second + dy[i];
if (e<1 || e>n || f<1 || f>m) continue;
if (dist[e][f] >= 0) continue;
if (g[e][f] == '#')continue;
if (st[e][f] == 1) continue;
q.push({ e,f });
st[e][f] == 1;
dist[e][f] = dist[t.first][t.second] + 1;
if (g[e][f] == '=')return dist[e][f];
}
}return -1;
}
int main() {
cin >> n >> m;
memset(dist, -1, sizeof dist);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> g[i][j];
if (g[i][j] == '@') {
c = i;
d = j;
}
}
}int res = bfs(c, d);
cout << res;
return 0;
}