暴搜
// LUOGU_RID: 167612453
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1010;
const int INF = 1e9;
struct node {
int x, y;
};
int d[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int n, m;
int ans;
int dis_1[MAXN][MAXN];
int dis_2[MAXN][MAXN];
int dis_3[MAXN][MAXN];
char a[MAXN][MAXN];
queue <node> q1, q2, q3;
void init() {
ans = INF;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
dis_1[i][j] = dis_2[i][j] = dis_3[i][j] = INF;
}
}
}
void bfs() {
while (q1.size()) {
int now_x = q1.front().x;
int now_y = q1.front().y;
q1.pop();
for (int i = 0; i < 4; ++i) {
int to_x = now_x + d[i][0];
int to_y = now_y + d[i][1];
int val = dis_1[now_x][now_y] + 1;
if (a[to_x][to_y] != '.') {
--val;
}
if (to_x && to_y && to_x <= n && to_y <= m && a[to_x][to_y] != '#' && val < dis_1[to_x][to_y]) {
dis_1[to_x][to_y] = val;
q1.push((node){to_x, to_y});
}
}
}
while (q2.size()) {
int now_x = q2.front().x;
int now_y = q2.front().y;
q2.pop();
for (int i = 0; i < 4; ++i) {
int to_x = now_x + d[i][0];
int to_y = now_y + d[i][1];
int val = dis_2[now_x][now_y] + 1;
if (a[to_x][to_y] != '.') {
--val;
}
if (to_x && to_y && to_x <= n && to_y <= m && a[to_x][to_y] != '#' && val < dis_2[to_x][to_y]) {
dis_2[to_x][to_y] = val;
q2.push((node){to_x, to_y});
}
}
}
while (q3.size()) {
int now_x = q3.front().x;
int now_y = q3.front().y;
q3.pop();
for (int i = 0; i < 4; ++i) {
int to_x = now_x + d[i][0];
int to_y = now_y + d[i][1];
int val = dis_3[now_x][now_y] + 1;
if (a[to_x][to_y] != '.') {
--val;
}
if (to_x && to_y && to_x <= n && to_y <= m && a[to_x][to_y] != '#' && val < dis_3[to_x][to_y]) {
dis_3[to_x][to_y] = val;
q3.push((node){to_x, to_y});
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
init();
for (int i = 1; i <= n; ++i) {
scanf("%s", a[i] + 1);
for (int j = 1; j <= m; ++j) {
if (a[i][j] == '1') {
q1.push((node){i, j});
dis_1[i][j] = 0;
} else if (a[i][j] == '2') {
q2.push((node){i, j});
dis_2[i][j] = 0;
} else if (a[i][j] == '3') {
q3.push((node){i, j});
dis_3[i][j] = 0;
}
}
}
bfs();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (dis_1[i][j] >= INF || dis_2[i][j] >= INF || dis_3[i][j] >= INF) {
continue;
}
if (a[i][j] == '.') {
ans = min(ans, dis_1[i][j] + dis_2[i][j] + dis_3[i][j] - 2);
} else {
ans = min(ans, dis_1[i][j] + dis_2[i][j] + dis_3[i][j]);
}
}
}
if (ans >= INF) {
printf("-1");
} else {
printf("%d", ans);
}
return 0;
}