#include <bits/stdc++.h>
using namespace std;
int a, z, b, c, n, m, rr[5][5], pat[5][2009][2009];
char d[2009][2009];
int tox[] = {-1, 1, 0, 0}, toy[] = {0, 0, -1, 1};
queue<pair<int, int> > Q;
int ok(int x, int y) {
  if (x >= 1 && x <= n && y >= 1 && y <= m) return 1;
  return 0;
}
void gothen(int x) {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (d[i][j] == char(x + '0'))
        pat[x][i][j] = 0, Q.push(make_pair(i, j));
      else
        pat[x][i][j] = 100000009;
    }
  }
  while (!Q.empty()) {
    pair<int, int> tr = Q.front();
    if (d[tr.first][tr.second] != '.')
      rr[x][d[tr.first][tr.second] - '0'] = min(
          rr[x][d[tr.first][tr.second] - '0'], pat[x][tr.first][tr.second] - 1);
    Q.pop();
    for (int i = 0; i < 4; i++) {
      int gox = tr.first + tox[i];
      int goy = tr.second + toy[i];
      if (pat[x][gox][goy] > pat[x][tr.first][tr.second] + 1 &&
          d[gox][goy] != '#' && ok(gox, goy))
        pat[x][gox][goy] = pat[x][tr.first][tr.second] + 1,
        Q.push(make_pair(gox, goy));
    }
  }
}
void icandoittoo() {
  int uy = rr[1][2] + rr[1][3];
  int yu = rr[2][1] + rr[2][3];
  int yy = rr[3][1] + rr[3][2];
  int real = min(uy, min(yu, yy));
  real += 2;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (pat[1][i][j] != 100000009 && pat[2][i][j] != 100000009 &&
          pat[3][i][j] != 100000009)
        real = min(real, pat[1][i][j] + pat[2][i][j] + pat[3][i][j]);
    }
  }
  if (real >= 100000009)
    cout << -1 << endl;
  else
    cout << real - 2 << endl;
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> d[i][j];
  for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) rr[i][j] = 100000009;
    rr[i][i] = 0;
  }
  for (int i = 1; i <= 3; i++) gothen(i);
  icandoittoo();
  return 0;
}
