#include <bits/stdc++.h>
using namespace std;
const long long maxN = 1e3 + 13, INF = 1e9 + 13;
long long n, m, d, ans = INF, dis[5][maxN][maxN], shp[10][10];
long long gox[4] = {0, 0, 1, -1}, goy[4] = {-1, 1, 0, 0};
char a[maxN][maxN];
bool mark[maxN][maxN];
vector<pair<long long, long long>> vec[maxN];
bool can(long long x, long long y) {
  if (x >= 1 && x <= n && y >= 1 && y <= m) return 1;
  return 0;
}
void dfs(long long x, long long y, char t) {
  mark[x][y] = 1;
  vec[d].push_back({x, y});
  for (long long i = 0; i < 4; i++) {
    if (can(x + gox[i], y + goy[i]) && !mark[x + gox[i]][y + goy[i]] &&
        a[x + gox[i]][y + goy[i]] == t) {
      dfs(x + gox[i], y + goy[i], t);
    }
  }
}
void sp(long long t) {
  memset(dis[t], -1, sizeof dis[t]);
  queue<pair<long long, long long>> qu;
  char ch;
  for (long long i = 0; i < vec[t].size(); i++) {
    qu.push(vec[t][i]);
    ch = a[vec[t][i].first][vec[t][i].second];
    dis[t][vec[t][i].first][vec[t][i].second] = 0;
  }
  while (!qu.empty()) {
    auto u = qu.front();
    qu.pop();
    long long x = u.first, y = u.second, curdis = dis[t][x][y];
    for (long long i = 0; i < 4; i++) {
      if (can(x + gox[i], y + goy[i]) && dis[t][x + gox[i]][y + goy[i]] == -1) {
        if (a[x + gox[i]][y + goy[i]] == '.') {
          dis[t][x + gox[i]][y + goy[i]] = curdis + 1;
          qu.push({x + gox[i], y + goy[i]});
        } else if (a[x + gox[i]][y + goy[i]] != '#') {
          shp[ch - '0' - 1][a[x + gox[i]][y + goy[i]] - '0' - 1] = min(
              shp[ch - '0' - 1][a[x + gox[i]][y + goy[i]] - '0' - 1], curdis);
        }
      }
    }
  }
}
int32_t main() {
  cin >> n >> m;
  for (long long i = 1; i <= n; i++) {
    string s;
    cin >> s;
    for (long long j = 1; j <= m; j++) a[i][j] = s[j - 1];
  }
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      if (a[i][j] != '#' && a[i][j] != '.' && !mark[i][j]) {
        dfs(i, j, a[i][j]);
        d++;
      }
    }
  }
  memset(shp, 63, sizeof shp);
  sp(0);
  sp(1);
  sp(2);
  for (long long i = 1; i <= n; i++)
    for (long long j = 1; j <= m; j++) {
      if (a[i][j] == '.') {
        if (dis[0][i][j] != -1 && dis[1][i][j] != -1 && dis[2][i][j] != -1)
          ans = min(ans, dis[0][i][j] + dis[1][i][j] + dis[2][i][j] - 2);
      }
    }
  ans = min(ans, shp[0][1] + shp[0][2]);
  ans = min(ans, shp[1][0] + shp[1][2]);
  ans = min(ans, shp[2][0] + shp[2][1]);
  if (ans < INF)
    cout << ans << endl;
  else
    cout << -1 << endl;
}
