#include <bits/stdc++.h>
using namespace std;
const int inft = 1000000009;
const int mod = 1000000007;
const int MAXN = 1000006;
const int dx[4] = {0, -1, 0, 1};
const int dy[4] = {1, 0, -1, 0};
int n, m;
vector<vector<char> > S;
int bfs2(const char *cc) {
  vector<vector<vector<int> > > D(
      3, vector<vector<int> >(n, vector<int>(m, inft)));
  for (int c = 0; c < (3); ++c) {
    queue<pair<int, int> > Q;
    for (int i = 0; i < (n); ++i)
      for (int j = 0; j < (m); ++j)
        if (S[i][j] == cc[c]) {
          D[c][i][j] = 0;
          Q.push(pair<int, int>(i, j));
        }
    while (!Q.empty()) {
      int first = Q.front().first, second = Q.front().second;
      Q.pop();
      int d = D[c][first][second];
      for (int h = 0; h < (4); ++h) {
        int nx = first + dx[h], ny = second + dy[h];
        if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
        if (D[c][nx][ny] < inft) continue;
        if (S[nx][ny] == '#') continue;
        D[c][nx][ny] = d + 1;
        Q.push(pair<int, int>(nx, ny));
      }
    }
  }
  int ret = inft;
  for (int i = 0; i < (n); ++i)
    for (int j = 0; j < (m); ++j)
      if (S[i][j] == '.')
        ret =
            min((long long)ret, 0LL + D[0][i][j] + D[1][i][j] + D[2][i][j] - 2);
  return ret;
}
pair<int, int> bfs(int from, int tox, int toy) {
  vector<vector<int> > D(n, vector<int>(m, inft));
  queue<pair<int, int> > Q;
  for (int i = 0; i < (n); ++i)
    for (int j = 0; j < (m); ++j)
      if (S[i][j] == from) {
        D[i][j] = -1;
        Q.push(pair<int, int>(i, j));
      }
  while (!Q.empty()) {
    int first = Q.front().first, second = Q.front().second;
    Q.pop();
    int d = D[first][second];
    for (int h = 0; h < (4); ++h) {
      int nx = first + dx[h], ny = second + dy[h];
      if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
      if (D[nx][ny] < inft) continue;
      if (S[nx][ny] == '#') continue;
      D[nx][ny] = d + 1;
      Q.push(pair<int, int>(nx, ny));
    }
  }
  pair<int, int> ret(inft, inft);
  for (int i = 0; i < (n); ++i)
    for (int j = 0; j < (m); ++j)
      if (S[i][j] == tox) ret.first = min(ret.first, D[i][j]);
  for (int i = 0; i < (n); ++i)
    for (int j = 0; j < (m); ++j)
      if (S[i][j] == toy) ret.second = min(ret.second, D[i][j]);
  return ret;
}
void solve() {
  scanf("%d%d", &n, &m);
  S.resize(n, vector<char>(m + 1));
  for (int i = 0; i < (n); ++i) scanf("%s", &S[i][0]);
  for (int i = 0; i < (n); ++i) S[i].pop_back();
  pair<int, int> A[3];
  for (int i = 0; i < (3); ++i)
    A[i] = bfs('1' + i, '1' + (i + 1) % 3, '1' + (i + 2) % 3);
  int best = bfs2("123");
  for (int i = 0; i < (3); ++i) best = min(best, A[i].first + A[i].second);
  if (best == inft) best = -1;
  printf("%d\n", best);
}
int main() {
  int te = 1;
  for (int ti = 0; ti < (te); ++ti) solve();
  return 0;
}
