题意:这里写链接内容
#include<iostream>
#include<algorithm>
#include<queue>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
#define maxn 1010
ll h,w,n,sx,sy,ex,ey,ans=0,d[maxn][maxn];
ll dir[4][2]={-1,0,1,0,0,1,0,-1};
char mp[maxn][maxn];
void find(int x){
x+=1;
char tmp=x+'0'; //数字转字符+'0',字符转数字-'0'
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
if(mp[i][j]==tmp){
ex=i;ey=j;
break;
}
}
}
}
//广搜
ll bfs(ll sx,ll sy,ll ex,ll ey){
queue<PII> que;
for(int i=0;i<h;i++)
for(int j=0;j<w;j++) d[i][j]=inf;
d[sx][sy]=0;
que.push(PII(sx,sy));
while(!que.empty()){
PII p=que.front(); que.pop();
if(p.first==ex&&p.second==ey) break;
for(int i=0;i<4;i++){
ll nx=p.first+dir[i][0];
ll ny=p.second+dir[i][1];
if(d[nx][ny]==inf &&nx>=0&&nx<h&&ny<w&&mp[nx][ny]!='X'){
que.push(PII(nx,ny));
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
return d[ex][ey];
}
int main(){
cin>>h>>w>>n;
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
cin>>mp[i][j];
if(mp[i][j]=='S'){
sx=i,sy=j;
}
}
}
for(int i=0;i<n;i++){
find(i);
// cout<<"sx,sy="<<sx<<sy<<" ex,ey="<<ex<<ey<<endl;
ans+=bfs(sx,sy,ex,ey);
sx=ex,sy=ey;
}
cout<<ans<<endl;
return 0;
}