#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
using dd = long double;
namespace {
static bool constexpr dbg = 0;
ll constexpr N = 1.1e3, INF = LONG_LONG_MAX / 10;
ll n, m;
string s[N];
ll d[5][N][N];
void foo(char c) {
  auto &cd = d[c - '1' + 1];
  deque<pll> q;
  for (ll i = 0; i < (ll)(n); ++i)
    for (ll j = 0; j < (ll)(m); ++j)
      if (s[i][j] == c) {
        cd[i][j] = 0;
        q.emplace_back(i, j);
      }
  while (q.size()) {
    ll x = q.front().first, y = q.front().second;
    q.pop_front();
    initializer_list<pll> de = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (auto const &it : de) {
      ll nx = x + it.first, ny = y + it.second;
      if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '#' ||
          cd[nx][ny] <= cd[x][y] + 1)
        continue;
      cd[nx][ny] = cd[x][y] + 1;
      q.emplace_back(nx, ny);
    }
  }
}
void init() {
  cin >> n >> m;
  for (ll i = 0; i < (ll)(n); ++i) cin >> s[i];
}
void solve() {
  for (ll i = 0; i < (ll)(4); ++i)
    for (ll j = 0; j < (ll)(N); ++j)
      for (ll k = 0; k < (ll)(N); ++k) d[i][j][k] = INF;
  foo('1');
  foo('2');
  foo('3');
  ll res, d12, d23, d31;
  res = d12 = d23 = d31 = INF;
  for (ll i = 0; i < (ll)(n); ++i)
    for (ll j = 0; j < (ll)(m); ++j)
      if (s[i][j] != '#') {
        if (s[i][j] == '.')
          res = min(res, d[1][i][j] + d[2][i][j] + d[3][i][j] - 2);
        if (s[i][j] == '1') {
          d12 = min(d12, d[2][i][j] - 1);
          d31 = min(d31, d[3][i][j] - 1);
        }
        if (s[i][j] == '2') {
          d12 = min(d12, d[1][i][j] - 1);
          d23 = min(d23, d[3][i][j] - 1);
        }
        if (s[i][j] == '3') {
          d23 = min(d23, d[2][i][j] - 1);
          d31 = min(d31, d[1][i][j] - 1);
        }
      }
  do {
    if (dbg) printf("d12 = %lld, d23 = %lld, d31 = %lld\n", d12, d23, d31);
  } while (0);
  vector<ll> v = {d12, d23, d31};
  sort(v.begin(), v.end());
  res = min(res, v[0] + v[1]);
  cout << (res >= INF - 10 ? -1 : res);
}
}  // namespace
int main() {
  if (!dbg) {
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
  }
  cout << fixed << setprecision(20);
  init();
  solve();
  return 0;
}
