import core.stdc.stdio;
import std.algorithm;
   
char[][] mapdata;
bool[] visited;
int[3][] queue;
int w,h,n;
   
int len(int[2] p1,int[2] p2){
 visited[] = false;
 queue[0]=[p1[0],p1[1],0];
 visited[p1[0]*w+p1[1]] = true;
 int[] dx = [0,-1,0,1];
 int[] dy = [-1,0,1,0];
 int qc=1;
 for(int i=0;i<w*h;i++){
  int y=queue[i][0];
  int x=queue[i][1];
  int s=queue[i][2];
  if(y==p2[0]&&x==p2[1])
   return s;
  for(int k=0;k<4;k++){
   int ny = y+dy[k];
   int nx = x+dx[k];
   if(0<=ny&&ny<h&&0<=nx&&nx<w&&mapdata[ny][nx]!='X'&&!visited[ny*w+nx]){
    visited[ny*w+nx]=true;
    queue[qc++] = [ny,nx,s+1];
   }
  }
 }
 return 114514;
}
   
void main(){
 scanf("%d%d%d",&h,&w,&n);
 int[2][] poses = new int[2][n+1];
 mapdata = new char[][h];
 visited = new bool[w*h];
 queue = new int[3][w*h];
 for(int i=0;i<h;i++){
  mapdata[i] = new char[w+1];
  scanf("%s",mapdata[i].ptr);
  foreach(int j,c;mapdata[i]){
   if(c=='S')
    poses[0] = [i,j];
   else if('1'<=c&&c<='9')
    poses[c-'0'] = [i,j];
  }
 }
 int ans=0;
 for(int i=0;i<n;i++)
  ans += len(poses[i],poses[i+1]);
 printf("%d\n",ans);
}