# include<iostream># include<cstdio># include<set>usingnamespace std ;struct Edge
{int to , next , w ;};
Edge g[400005];int dis[400005];int gsz ;int fte[400005];int fast[30];int num ;int dx[4]={-1,0,0,1};int dy[4]={0,-1,1,0};voidaddedge(int x ,int y ,int z ){
g[++ gsz]=( Edge ){ y , fte[x], z };
fte[x]= gsz ;}int n , m ;int s , t ;
set < pair <int,int>> heap ;int total ;voiddij(int s ){for(int i =1; i <= total ; i++){
dis[i]=2147483647;}
dis[s]=0;
heap.insert(make_pair(0, s ));for(int i =1; i <= total ; i++){int x = heap.begin()-> second ;int d = heap.begin()-> first ;
heap.erase(make_pair( d , x ));for(int i = fte[x]; i ; i = g[i].next ){int y = g[i].to ;if( dis[x]+ g[i].w >= dis[y])continue;
heap.erase(make_pair( dis[y], y ));
dis[y]= dis[x]+ g[i].w ;
heap.insert(make_pair( dis[y], y ));}}}intmain(){scanf("%d%d",&n ,&m);
total =2* n * m ;for(int i =1; i <= n ; i++){scanf("\n");for(int j =1; j <= m ; j++){int eid =( i -1)* m + j ;char c ;scanf("%c",&c);if( c =='#'){continue;}for(int k =0; k <=3; k++){int nowx = i + dx[k];int nowy = j + dy[k];int noweid = m *( nowx -1)+ nowy ;if( nowx >=1&& nowx <= n && nowy >=1&& nowy <= m ){addedge( noweid *2-1, eid *2,1);}}if( c >='A'&& c <='Z'){if( fast[c -'A']){addedge( fast[c -'A']*2, eid *2-1,0);addedge( eid *2, fast[c -'A']*2-1,0);}
fast[c -'A']= eid ;continue;}addedge( eid *2, eid *2-1,0);if( c =='@'){
s = eid *2-1;continue;}if( c =='='){
t = eid *2;continue;}if( c =='.')continue;}}dij( s );printf("%d\n", dis[t]);return0;}