#include <bits/stdc++.h>
using namespace std;
int n, m;
int pos[] = {1, 0, -1, 0, 0, 1, 0, -1};
int ph[5][5];
int D[5][1005][1005];
char v[1005][1005];
queue<pair<int, int> > Q;
void bf(int a) {
  for (int i = 1; i <= n; i++) {
    for (int h = 1; h <= m; h++) {
      D[a][i][h] = 100000007;
      if (v[i][h] == a + '0') {
        D[a][i][h] = 0;
        Q.push({i, h});
      }
    }
  }
  while (!Q.empty()) {
    int i = Q.front().first;
    int h = Q.front().second;
    Q.pop();
    for (int j = 0; j < 8; j += 2) {
      int x = i + pos[j];
      int y = h + pos[j + 1];
      if (x > 0 && y > 0 && x <= n && y <= m && v[x][y] != '#' &&
          D[a][x][y] > D[a][i][h] + 1) {
        D[a][x][y] = D[a][i][h] + 1;
        Q.push({x, y});
      }
    }
  }
  for (int i = 1; i <= n; i++)
    for (int h = 1; h <= m; h++)
      if (v[i][h] >= '1' && v[i][h] <= '3')
        ph[a][v[i][h] - '0'] = min(ph[a][v[i][h] - '0'], D[a][i][h] - 1);
}
int ok() {
  int a = ph[1][2] + ph[2][3];
  int b = ph[1][2] + ph[1][3];
  int c = ph[2][3] + ph[3][1];
  int mn = min(a, min(c, b)) + 2;
  for (int i = 1; i <= n; i++)
    for (int h = 1; h <= m; h++)
      if (D[1][i][h] != 100000007 && D[2][i][h] != 100000007 &&
          D[3][i][h] != 100000007)
        mn = min(mn, D[1][i][h] + D[2][i][h] + D[3][i][h]);
  if (mn >= 100000007) return -1;
  return mn - 2;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++)
    for (int h = 1; h <= m; h++) cin >> v[i][h];
  for (int i = 1; i <= 3; i++)
    for (int h = 1; h <= 3; h++) ph[i][h] = 100000007;
  for (int i = 1; i <= 3; i++) bf(i);
  printf("%d\n", ok());
}
