#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 0, 1, -1}, dy[] = {0, 1, -1, 0, 0}, n, m;
char b[1010][1010];
int d12, d13, d23;
int dis[1010][1010];
int d[1010][1010][5];
void aa(int x) {
  queue<pair<int, int> > q;
  int i, j, nx, ny, tx, ty;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (b[i][j] == x + '0') q.push(make_pair(i, j)), d[i][j][x] = 0;
  while (!q.empty()) {
    nx = q.front().first;
    ny = q.front().second;
    q.pop();
    for (i = 1; i <= 4; i++) {
      tx = nx + dx[i];
      ty = ny + dy[i];
      if (tx && ty && tx <= n && ty <= m && d[tx][ty][x] == 0x3f3f3f3f &&
          b[tx][ty] == '.') {
        d[tx][ty][x] = d[nx][ny][x] + 1;
        q.push(make_pair(tx, ty));
      }
    }
  }
}
int bb(int x, int y) {
  memset(dis, 0x3f, sizeof(dis));
  queue<pair<int, int> > q;
  int i, j, nx, ny, tx, ty;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (b[i][j] == x + '0') q.push(make_pair(i, j)), dis[i][j] = 0;
  while (!q.empty()) {
    nx = q.front().first;
    ny = q.front().second;
    q.pop();
    for (i = 1; i <= 4; i++) {
      tx = nx + dx[i];
      ty = ny + dy[i];
      if (tx && ty && tx <= n && ty <= m && dis[tx][ty] == 0x3f3f3f3f &&
          b[tx][ty] != '#') {
        if (b[tx][ty] == y + '0') return dis[nx][ny];
        dis[tx][ty] = dis[nx][ny] + 1;
        q.push(make_pair(tx, ty));
      }
    }
  }
  return 0x3f3f3f3f;
}
int main() {
  int ans = 0x3f3f3f3f;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) scanf("%s", b[i] + 1);
  d12 = bb(1, 2);
  d13 = bb(1, 3);
  d23 = bb(2, 3);
  ans = min(ans, d12 + d13);
  ans = min(ans, d12 + d23);
  ans = min(ans, d13 + d23);
  memset(d, 0x3f, sizeof(d));
  aa(1), aa(2), aa(3);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (b[i][j] == '.')
        ans = min((long long)ans,
                  (long long)d[i][j][1] + d[i][j][2] + d[i][j][3] - 2);
  printf("%d\n", (ans == 0x3f3f3f3f) ? -1 : ans);
}
