#include <bits/stdc++.h>
using namespace std;
const int INF = int(1e9);
const long long INFll = 1ll * INF * INF;
const long double ldINF = 1e+018;
const long double EPS = 0.000000001;
const int sdx[4] = {-1, 0, 1, 0};
const int sdy[4] = {0, 1, 0, -1};
template <typename T>
ostream& operator<<(ostream& out, pair<T, T>& a) {
  out << a.first << " " << a.second;
  return out;
}
template <typename T>
istream& operator>>(istream& in, pair<T, T>& a) {
  in >> a.first >> a.second;
  return in;
}
template <typename T>
istream& operator>>(istream& in, vector<T>& a) {
  for (int i = 0; i < a.size(); ++i) in >> a[i];
  return in;
}
template <typename T>
ostream& operator<<(ostream& out, vector<T> a) {
  for (int i = 0; i < a.size(); ++i)
    if (i == a.size() - 1)
      out << a[i];
    else
      out << a[i] << " ";
}
char c[1100][1100];
long long d[6][1101][1111];
int main() {
  int n, m;
  cin >> n >> m;
  scanf("\n");
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) scanf("%c", &c[i][j]);
    scanf("\n");
  }
  for (int k = 0; k < 3; k++)
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) d[k][i][j] = INF;
  for (int k = 0; k < 3; k++) {
    deque<pair<int, int> > q;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if (c[i][j] == char((k + 1) + '0')) {
          q.push_front(make_pair(i, j));
          d[k][i][j] = 0;
        }
    while (!q.empty()) {
      int x = q.front().first, y = q.front().second;
      q.pop_front();
      for (int i = 0; i < 4; i++) {
        int x1 = x + sdx[i], y1 = y + sdy[i];
        if (x1 < 0 || y1 < 0 || x1 >= n || y1 >= m || c[x1][y1] == '#')
          continue;
        int add;
        add = d[k][x][y] + 1;
        if (c[x1][y1] != '.' && c[x1][y1] != '#') add--;
        if (d[k][x1][y1] > add) {
          d[k][x1][y1] = add;
          if (c[x1][y1] == '.')
            q.push_back(make_pair(x1, y1));
          else
            q.push_back(make_pair(x1, y1));
        }
      }
    }
  }
  long long mn = INF;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (c[i][j] == '#') continue;
      if (d[0][i][j] == INF || d[1][i][j] == INF || d[2][i][j] == INF) continue;
      long long dist = d[0][i][j] + d[1][i][j] + d[2][i][j];
      if (c[i][j] == '.') dist -= 2;
      mn = min(mn, dist);
    }
  if (mn == INF)
    cout << -1 << endl;
  else
    cout << mn << endl;
  return 0;
}
