#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long f = 1, sum = 0;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    sum = sum * 10 + c - '0';
    c = getchar();
  }
  return sum * f;
}
const int MAXN = 1010;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
char s[MAXN];
int a[MAXN][MAXN], dis[3][MAXN][MAXN], n, m;
queue<int> qx, qy;
int cnt;
void bfs(int num) {
  while (!qx.empty()) qx.pop(), qy.pop();
  num--;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] == (num + 1)) {
        qx.push(i), qy.push(j);
        dis[num][i][j] = 0;
      }
  while (!qx.empty()) {
    int x = qx.front(), y = qy.front();
    qx.pop(), qy.pop();
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i], ny = y + dy[i];
      if (nx <= 0 || ny <= 0 || nx > n || ny > m || a[nx][ny] == -1) continue;
      if (dis[num][x][y] + 1 < dis[num][nx][ny]) {
        dis[num][nx][ny] = dis[num][x][y] + 1;
        qx.push(nx), qy.push(ny);
      }
    }
  }
}
int work() {
  vector<int> v;
  for (int i = 1; i <= 3; i++) {
    for (int j = i + 1; j <= 3; j++) {
      int now = 0x3f3f3f3f;
      for (int x = 1; x <= n; x++)
        for (int y = 1; y <= m; y++)
          if (a[x][y] == j) now = min(now, dis[i - 1][x][y]);
      v.push_back(now);
    }
  }
  sort(v.begin(), v.end());
  if (v[0] == 0x3f3f3f3f) return 0x3f3f3f3f;
  if (v[1] == 0x3f3f3f3f) return 0x3f3f3f3f;
  return v[0] + v[1] - 2;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", s + 1);
    for (int j = 1; j <= m; j++) {
      if (s[j] > '0' && s[j] <= '3')
        a[i][j] = (int)s[j] - '0';
      else if (s[j] == '#')
        a[i][j] = -1;
    }
  }
  memset(dis, 0x3f, sizeof(dis));
  for (int i = 1; i <= 3; i++) bfs(i);
  int ans = work();
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      if (a[i][j] != 0) continue;
      int tmp = 0;
      for (int k = 1; k <= 3; k++) {
        if (dis[k - 1][i][j] == 0x3f3f3f3f) {
          tmp = 0x3f3f3f3f;
          break;
        }
        tmp += dis[k - 1][i][j];
      }
      tmp -= 2;
      ans = min(ans, tmp);
    }
  if (ans == 0x3f3f3f3f || ans == 0x3f3f3f3f - 2) ans = -1;
  cout << ans;
  return 0;
}
