#include <bits/stdc++.h>
using namespace std;
char str[1005][1005];
int n, m;
int dis[4][1005][1005];
struct Node {
  int x, y;
  Node() {}
  Node(int xx, int yy) { x = xx, y = yy; }
};
int dir[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int p[4];
bool ok(int x, int y) {
  if (x < 1 || x > n || y < 1 || y > m) return false;
  return true;
}
void slove(int ind) {
  queue<Node> que;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (str[i][j] == '0' + ind)
        que.push(Node(i, j)), dis[ind][i][j] = 0, p[ind] = 0;
    }
  }
  Node tmp, nxt;
  while (!que.empty()) {
    tmp = que.front();
    que.pop();
    for (int k = 0; k < 4; k++) {
      nxt.x = tmp.x + dir[k][0];
      nxt.y = tmp.y + dir[k][1];
      if (!ok(nxt.x, nxt.y)) continue;
      if (dis[ind][nxt.x][nxt.y] != -1) continue;
      if (str[nxt.x][nxt.y] == '#') continue;
      dis[ind][nxt.x][nxt.y] = dis[ind][tmp.x][tmp.y] + 1;
      if (str[nxt.x][nxt.y] >= '1' && str[nxt.x][nxt.y] <= '3') {
        if (str[nxt.x][nxt.y] == '1' && p[1] == -1)
          p[1] = dis[ind][nxt.x][nxt.y];
        if (str[nxt.x][nxt.y] == '2' && p[2] == -1)
          p[2] = dis[ind][nxt.x][nxt.y];
        if (str[nxt.x][nxt.y] == '3' && p[3] == -1)
          p[3] = dis[ind][nxt.x][nxt.y];
      }
      que.push(Node(nxt.x, nxt.y));
    }
  }
}
int main() {
  while (scanf("%d%d", &n, &m) != EOF) {
    for (int i = 1; i <= n; i++) {
      scanf("%s", str[i] + 1);
    }
    int ans = -1;
    memset(dis[1], -1, sizeof(dis[1]));
    memset(p, -1, sizeof(p));
    slove(1);
    if (p[1] != -1 && p[2] != -1 && p[3] != -1)
      ans =
          ans == -1 ? p[1] + p[2] + p[3] - 2 : min(ans, p[1] + p[2] + p[3] - 2);
    memset(dis[2], -1, sizeof(dis[2]));
    memset(p, -1, sizeof(p));
    slove(2);
    if (p[1] != -1 && p[2] != -1 && p[3] != -1)
      ans =
          ans == -1 ? p[1] + p[2] + p[3] - 2 : min(ans, p[1] + p[2] + p[3] - 2);
    memset(dis[3], -1, sizeof(dis[3]));
    memset(p, -1, sizeof(p));
    slove(3);
    if (p[1] != -1 && p[2] != -1 && p[3] != -1)
      ans =
          ans == -1 ? p[1] + p[2] + p[3] - 2 : min(ans, p[1] + p[2] + p[3] - 2);
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        if (dis[1][i][j] == -1) continue;
        if (dis[2][i][j] == -1) continue;
        if (dis[3][i][j] == -1) continue;
        ans = ans == -1
                  ? dis[1][i][j] + dis[2][i][j] + dis[3][i][j] - 2
                  : min(ans, dis[1][i][j] + dis[2][i][j] + dis[3][i][j] - 2);
      }
    }
    printf("%d\n", ans);
  }
  return 0;
}
