#include <cstdio>
#include <queue>
#include <vector>
#define SIZE 300 + 5
using namespace std;
struct node2{
int x, y, t;
node2() {
}
node2(const int &xx, const int &yy, const int &tt) {
x = xx, y = yy, t = tt;
}
};
char map[SIZE][SIZE];
bool vis[SIZE][SIZE];
int n, m, walk[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int bfs(const int &x, const int &y);
int main() {
freopen("cpp.in", "r", stdin);
freopen("cpp.out", "w", stdout);
int a, b;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i) {
scanf("%s", &map[i]);
for (int j = 0; j < m; ++j) {
if (map[i][j] == '@') {
a = i, b = j;
}
}
}
printf("%d", bfs(a, b));
return 0;
}
int bfs(const int &x, const int &y) {
queue<node2> q;
q.push(node2(x, y, 0));
vis[x][y] = true;
while (!q.empty()) {
if (map[q.front().x][q.front().y] >= 'A' && map[q.front().x][q.front().y] <= 'Z') {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (!(i == q.front().x && j == q.front().y) && map[i][j] == map[q.front().x][q.front().y]) {
q.front() = node2(i, j, q.front().t);
i = n, j = m;
}
}
}
}
node2 now = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int nx = now.x + walk[i][0];
int ny = now.y + walk[i][1];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && !vis[nx][ny] && map[nx][ny] != '#') {
if (map[nx][ny] == '=') {
return now.t + 1;
}
q.push(node2(nx, ny, now.t + 1));
vis[nx][ny] = true;
}
}
}
return -1;
}