#include <bits/stdc++.h>
using namespace std;
const long long Maxn = 5e5 + 7;
const long long Max = 1e3 + 7;
const long long Mod = 1e9 + 7;
const long long Inf = 1e9 + 7;
long long n, m, a[Max][Max], dis[Max][Max][10], d[10][10], ans = Inf;
long long X[] = {1, 0, -1, 0};
long long Y[] = {0, 1, 0, -1};
queue<pair<long long, long long> > q;
vector<pair<long long, long long> > V[10];
long long change(char t) {
  if (t == '.') return 1;
  if (t == '#') return 0;
  return t - '0' + 1;
}
void bfs(long long cnr) {
  while (q.size()) {
    pair<long long, long long> pos = q.front();
    long long x = pos.first, y = pos.second;
    q.pop();
    for (long long i = 0; i < 4; i++) {
      long long xx = X[i] + x, yy = Y[i] + y;
      if (a[xx][yy] && dis[xx][yy][cnr] > (dis[x][y][cnr]) + 1) {
        q.push(make_pair(xx, yy));
        dis[xx][yy][cnr] = dis[x][y][cnr] + 1;
      }
    }
  }
}
void dist_country(long long p, long long x, long long y) {
  for (long long i = 2; i <= 4; i++)
    d[p][i] = min(dis[x][y][i], d[p][i]), d[i][p] = min(dis[x][y][i], d[i][p]);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      dis[i][j][4] = dis[i][j][2] = dis[i][j][3] = Inf;
      char t;
      cin >> t;
      a[i][j] = change(t);
      if (a[i][j] > 1)
        V[a[i][j]].push_back(make_pair(i, j)), dis[i][j][a[i][j]] = -1;
    }
  }
  for (long long i = 2; i <= 4; i++)
    for (long long j = 2; j <= 4; j++) d[i][j] = Inf;
  for (long long i = 2; i <= 4; i++) {
    for (long long j = 0; j < V[i].size(); j++) q.push(V[i][j]);
    bfs(i);
  }
  for (long long i = 1; i <= n; i++)
    for (long long j = 1; j <= m; j++) {
      if (a[i][j] == 1)
        ans = min(ans, dis[i][j][4] + dis[i][j][2] + dis[i][j][3]);
      else if (a[i][j] > 1)
        dist_country(a[i][j], i, j);
    }
  ans++;
  ans = min(ans, d[2][3] + d[2][4]);
  ans = min(ans, d[2][3] + d[3][4]);
  ans = min(ans, d[4][2] + d[4][3]);
  if (ans >= Mod)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
