题意:


思路:







#include <cstdio>
#include <deque>
using namespace std;
const int N = 1e3 + 5;
const int inf = 0x3f3f3f3f;
char mp[N][N];
bool vis[3][N][N];
int dist[3][N][N];
int n,m,dx[] = {1,-1,0,0},dy[] = {0,0,1,-1};
struct Node{
    int x,y,dis;
};
void bfs(int x){
    deque<Node> q;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= m;j++){
            if(mp[i][j] == '1' + x){
                q.push_back(Node{i,j,0});
            }
        }
    }
    int ans = inf;
    while(q.size()){
        Node u = q.front();
        q.pop_front();
        dist[x][u.x][u.y] = u.dis;
        for(int i = 0;i < 4;i++){
            int nx = u.x + dx[i],ny = u.y + dy[i];
            if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && !vis[x][nx][ny] && mp[nx][ny] != '#'){
                vis[x][nx][ny] = 1;
                if(mp[nx][ny] == '.'){
                    q.push_back(Node{nx,ny,u.dis + 1});
                }else{
                    q.push_front(Node{nx,ny,u.dis});
                }
            }
        }
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n;i++){
        scanf("%s",mp[i] + 1);
    }
    bfs(0),bfs(1),bfs(2);
    int ans = inf;
    for(int i = 1;i <= n;i++){
        for(int j = 1;j <= m;j++){
            if(mp[i][j] != '#' && vis[0][i][j] && vis[1][i][j] && vis[2][i][j]){
                if(mp[i][j] == '.'){
                    ans = min(ans,dist[0][i][j] + dist[1][i][j] + dist[2][i][j] - 2);
                }else ans = min(ans,dist[0][i][j] + dist[1][i][j] + dist[2][i][j]);
            }
        }
    }
    if(ans < inf) printf("%d\n",ans);
    else puts("-1");
    return 0;
}