题目链接

题意:





题解:











AC代码

/*
    Author:zzugzx
    Lang:C++
    Blog:blog.csdn.net/qq_43756519
*/
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define endl '\n'
#define SZ(x) (int)x.size()
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int mod=1e9+7;
//const int mod=998244353;
const double eps = 1e-10;
const double pi=acos(-1.0);
const int maxn=1e6+10;
const ll inf=0x3f3f3f3f;
const int dir[8][2]={{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};

int n,m;
int dis[1010][1010][4];
char g[1010][1010];
queue<pii> q;
void bfs(int x){
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            if(g[i][j]=='0'+x)
                q.push(mp(i,j)),dis[i][j][x]=0;
    while(!q.empty()){
        pii p=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            int dx=p.fi+dir[i][0];
            int dy=p.se+dir[i][1];
            if(dx<1||dx>n||dy<1||dy>m||g[dx][dy]=='#')continue;
            int v=(g[dx][dy]=='.');
            if(dis[p.fi][p.se][x]+v<dis[dx][dy][x]){
                dis[dx][dy][x]=dis[p.fi][p.se][x]+v;
                q.push(mp(dx,dy));
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>g[i]+1;
    memset(dis,inf,sizeof dis);
    bfs(1),bfs(2),bfs(3);
    ll ans=inf;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            ll tmp=0;
            for(int k=1;k<=3;k++)tmp+=dis[i][j][k];
            if(g[i][j]=='.')tmp-=2;
            ans=min(ans,tmp);
        }
    if(ans==inf)cout<<-1;
    else cout<<ans;
    return 0;
}