#include <bits/stdc++.h>
using namespace std;
struct xy
{
int x;
int y;
};
char d[300][300];
int b[300][300];
xy men[26][100000];
int ji[26];
int mc;
xy ed;
xy st;
int n,m;
queue<xy>q;
xy s1;
xy s2;
int now;
int fx[]={0,1,-1,0,0};
int fy[]={0,0,0,1,-1};
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>d[i][j];
if(d[i][j]=='@')
{
st.x=i;
st.y=j;
}
if(d[i][j]=='=')
{
ed.x=i;
ed.y=j;
}
if(d[i][j]>='A'&&d[i][j]<='Z')
{
mc=d[i][j]-'A';
men[mc][ji[mc]].x=i;
men[mc][ji[mc]].y=j;
ji[mc]++;
}
b[i][j]=-1;
}
}
q.push(st);
b[st.x][st.y]=0;
while(!q.empty())
{
s1=q.front();
now=b[s1.x][s1.y]+1;
for(int i=1;i<=4;i++)
{
s2.x=s1.x+fx[i];
s2.y=s1.y+fy[i];
if(s2.x<0||s2.x>=n||s2.y<0||s2.y>m||d[s2.x][s2.y]=='#')continue;
if(b[s2.x][s2.y]==-1)
{
if(d[s2.x][s2.y]=='.'||d[s2.x][s2.y]=='=')//不是字母
{
b[s2.x][s2.y]=now;
q.push(s2);
}
else//是字母
{
mc=d[s2.x][s2.y]-'A';
for(int j=0;j<ji[mc];j++)
{
if(men[mc][j].x!=s2.x&&men[mc][j].y!=s2.y&&b[men[mc][j].x][men[mc][j].y]==-1)
{
b[men[mc][j].x][men[mc][j].y]=now;
q.push(men[mc][j]);
}
}
}
}
}
q.pop();
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("%-3d",b[i][j]);
}
cout<<endl;
}
cout<<b[ed.x][ed.y];
return 0;
}