#include<bits/stdc++.h>
using namespace std;
int n,m,vis[310][310],a[310][310];
int st1,st2,en1,en2;
queue<int>q1;
queue<int>q2;
queue<int>q;
int s1,s2;
int ans=999999999;
bool check(int x,int y){
if (a[x][y]>='A'&&a[x][y]<='Z'){
return true;
}
return false;
}
void finds(int x,int y){
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
if (i!=x&&j!=y&&a[i][j]==a[x][y]){
s1=i;
s2=j;
return ;
}
}
}
}
int dx[5]={0,0,0,1,-1};
int dy[5]={0,1,-1,0,0};
void bfs(int b,int c){
q.push(0);
q1.push(b);
q2.push(c);
if (a[b][c]>='A'&&a[b][c]<='Z'){
finds(b,c);
}
vis[b][c]=1;
while (!q.empty()){
int x=q1.front();
int y=q2.front();
int z=q.front();
q.pop();
q1.pop();
q2.pop();
for (int i=1;i<=4;i++){
int xx=dx[i]+x;
int yy=dy[i]+y;
if (xx>0&&yy>0&&xx<=n&&yy<=m&&a[xx][yy]!=1&&vis[xx][yy]!=1){
if (xx==en1&&yy==en1){
ans=min(ans,z+1);
continue;
}
vis[xx][yy]=1;
if (!check(xx,yy)){
q.push(z+1);
q1.push(xx);
q2.push(yy);
continue;
}
else{
finds(xx,yy);
q.push(z+1);
q1.push(s1);
q2.push(s2);
continue;
}
}
}
}
}
int main(){
cin>>n>>m;
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
char h;
cin>>h;
if (h=='.'){
a[i][j]=1;
}
if (h>='A'&&h<='Z'){
a[i][j]=h;
}
if (h=='@'){
st1=i;
st2=j;
}
if (h=='='){
en1=i;
en2=j;
}
}
}
bfs(st1,st2);
cout<<ans;
return 0;
}