#include <bits/stdc++.h>
using namespace std;
template <class T>
inline T bigmod(T p, T e, T M) {
  long long ret = 1;
  for (; e > 0; e >>= 1) {
    if (e & 1) ret = (ret * p) % M;
    p = (p * p) % M;
  }
  return (T)ret;
}
template <class T>
inline T gcd(T a, T b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
template <class T>
inline T modinverse(T a, T M) {
  return bigmod(a, M - 2, M);
}
int dis[4][1001][1001], n, m;
;
queue<pair<int, int> > Q;
char pp[1011][1011];
int nxt[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void go(int c) {
  while (!Q.empty()) Q.pop();
  for (int i = (0); i < (n); ++i) {
    for (int j = (0); j < (m); ++j)
      if (pp[i][j] == '0' + c) {
        dis[c][i][j] = 0;
        Q.push(make_pair(i, j));
      }
  }
  while (!Q.empty()) {
    pair<int, int> p = Q.front();
    Q.pop();
    for (int i = (0); i < (4); ++i) {
      int x = p.first + nxt[i][0], y = p.second + nxt[i][1];
      if (x < 0 || x >= n || y < 0 || y >= m || pp[x][y] == '#') continue;
      if (dis[c][x][y] <= dis[c][p.first][p.second] + 1) continue;
      dis[c][x][y] = dis[c][p.first][p.second] + 1;
      Q.push(make_pair(x, y));
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  for (int i = (0); i < (n); ++i) cin >> pp[i];
  memset(dis, 126, sizeof dis);
  go(1);
  go(2);
  go(3);
  int res = INT_MAX / 3;
  for (int i = (1); i < (4); ++i) {
    int dd[4];
    memset(dd, 126, sizeof dd);
    dd[i] = 1;
    for (int j = (0); j < (n); ++j) {
      for (int k = (0); k < (m); ++k) {
        if (pp[j][k] >= '1' && pp[j][k] <= '3' && pp[j][k] != '0' + i)
          dd[pp[j][k] - '0'] = min(dd[pp[j][k] - '0'], dis[i][j][k]);
      }
    }
    long long sum = 0;
    for (int j = (1); j < (4); ++j) sum += dd[j] - 1;
    if (sum < res) res = sum;
  }
  for (int i = (0); i < (n); ++i) {
    for (int j = (0); j < (m); ++j) {
      if (pp[i][j] != '.') continue;
      long long sum = 1;
      for (int k = (1); k < (4); ++k) {
        sum += dis[k][i][j] - 1;
      }
      if (sum < res) res = sum;
    }
  }
  if (res > 10000000)
    cout << -1 << endl;
  else
    cout << res << endl;
}
