#include<bits/stdc++.h>
using namespace std;
int n,m,to[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
struct ak{
int tox,toy;
}cs[30][2];
struct ac{
int x,y,time;
bool v;
};
char a[303][303];
bool f[302][302];
queue<ac> Q,q;
int csz(int z,int x,int y){
if(cs[z][0].tox!=x||cs[z][0].toy!=y) return 0;
return 1;
}
bool pd(int x,int y){
if(x>0&&x<=n&&y>0&&y<=m) return true;
return false;
}
void bfs(ac sta){
f[sta.x][sta.y]=true;
sta.time=0;
Q.push(sta);
while(!Q.empty()||!q.empty()){
ac now,next;
if(!q.empty()){
now=q.front();
q.pop();
}else{
now=Q.front();
Q.pop();
}
int nx=now.x,ny=now.y;
if(a[nx][ny]=='='){
printf("%d",now.time);
exit(0);
}
if(a[nx][ny]=='.'||now.v==true){
for(int i=0;i<4;i++){
int tx=nx+to[i][0],ty=ny+to[i][1];
if(!f[tx][ty]&&a[tx][ty]!='#'&&pd(tx,ty)){
next.x==tx;
next.y=ty;
next.v=false;
next.time=now.time+1;
Q.push(next);
f[tx][ty]=true;
}
}
}else{
int cz=csz(a[nx][ny]-'A'+1,nx,ny);
next.x=cs[a[nx][ny]-'A'+1][cz].tox;
next.y=cs[a[nx][ny]-'A'+1][cz].toy;
next.time=now.time;
next.v=true;
q.push(next);
}
}
}
int main(){
scanf("%d%d",&n,&m);
int js[30];
ac s;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
if(a[i][j]=='@'){
s.x=i,s.y=j,s.time=0;
a[i][j]='.';
}else if(a[i][j]<='Z'&&a[i][j]>='A'){
js[a[i][j]-'A']++;
if(js[a[i][j]-'A']==1){
cs[a[i][j]-'A'+1][1].tox=i;
cs[a[i][j]-'A'+1][1].toy=j;
}
else{
cs[a[i][j]-'A'+1][0].tox=i;
cs[a[i][j]-'A'+1][0].toy=j;
}
}
}
}
for(int i=1;i<=26;i++){
if(js[i]==1){
int tx=cs[i][1].tox,ty=cs[i][1].toy;
a[tx][ty]='.';
}
}
bfs(s);
return 0;
}