#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node{
int x;
int y;
}q[90001];
node door[100][3];
int sx,sy,ex,ey,n,m,h,t,p[90001],a[330][330],vis[330][330],ans=0;
int dx[5]={0,1,-1,0,0},
dy[5]={0,0,0,1,-1};
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
char c;
cin>>c;
if(c=='#') a[i][j]=0;
else if(c=='.') a[i][j]=1;
else if(c=='@') sx=i,sy=j,a[i][j]=1;
else if(c=='=') ex=i,ey=j,a[i][j]=1;
else
{
a[i][j]=int(c);
if(door[int(c)][0].x==0)
{
door[int(c)][1].x=i;
door[int(c)][1].y=j;
}
else
{
door[int(c)][2].x=i;
door[int(c)][2].y=j;
}
door[int(c)][0].x++;
}
}
}
h=0,t=1;
q[t].x=sx;
q[t].y=sy;
vis[sx][sy]=1;
p[t]=h;
while(h<t)
{
h++;
for(int i=1;i<=4;i++)
{
int xx=q[h].x+dx[i],yy=q[h].y+dy[i];
if(xx>0&&yy>0&&xx<=n&&yy<=m&&vis[xx][yy]==0&&a[xx][yy]!=0)
{
vis[xx][yy]=1;
if(a[xx][yy]!=1)
{
int x1,y1;
if(xx==door[a[xx][yy]][1].x&&yy==door[a[xx][yy]][1].y)
{
x1=door[a[xx][yy]][2].x;
y1=door[a[xx][yy]][2].y;
}
else
{
x1=door[a[xx][yy]][1].x;
y1=door[a[xx][yy]][1].y;
}
xx=x1,yy=y1;
}
vis[xx][yy]=1;
t++;
q[t].x=xx,q[t].y=yy;
p[t]=h;
if(xx==ex&&yy==ey)
{
int k=p[t];
while(k!=0)
{
ans++;
k=p[k];
}
}
}
}
}
cout<<ans;
return 0;
}