#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
template <class T>
typename T::value_type arr_sum(const T& v, int n) {
  typename T::value_type sum = 0;
  for (int i = (0); i < (n); ++i) sum += v[i];
  return sum;
}
struct Sync_stdio {
  Sync_stdio() {
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
  }
} _sync_stdio;
struct Z {
  int first;
  int second;
  int dist;
};
vector<vector<vector<int>>> d(3);
vector<string> v;
int n, m;
void bfs(int x) {
  queue<Z> q;
  for (int i = (0); i < (n); ++i) {
    for (int j = (0); j < (m); ++j) {
      if (v[i][j] - '0' == x) {
        q.push({i, j, 0});
        d[x - 1][i][j] = 0;
      }
    }
  }
  while (q.size()) {
    Z t = q.front();
    q.pop();
    for (int i = (-1); i < (2); ++i) {
      for (int j = (-1); j < (2); ++j) {
        if (abs(i) + abs(j) != 1) {
          continue;
        }
        if (d[x - 1][t.first + i][t.second + j] != 5000000) {
          continue;
        }
        if (v[t.first + i][t.second + j] == '#') {
          continue;
        }
        if (v[t.first + i][t.second + j] == '.') {
          d[x - 1][t.first + i][t.second + j] = t.dist + 1;
          q.push({t.first + i, t.second + j, t.dist + 1});
        } else {
          d[x - 1][t.first + i][t.second + j] = t.dist;
          q.push({t.first + i, t.second + j, t.dist});
        }
      }
    }
  }
}
int main() {
  cin >> n >> m;
  v.assign(n + 2, string(m + 2, '#'));
  for (int i = (1); i < (n + 1); ++i) {
    cin >> v[i];
    v[i] = '#' + v[i] + '#';
  }
  n += 2;
  m += 2;
  for (int k = (0); k < (3); ++k) {
    d[k].assign(n, vector<int>(m, 5000000));
    bfs(k + 1);
  }
  vector<int> dist(3, 5000000);
  for (int k = (0); k < (3); ++k) {
    for (int i = (0); i < (n); ++i) {
      for (int j = (0); j < (m); ++j) {
        if (v[i][j] != (k + 1) % 3 + '1') {
          continue;
        }
        dist[k] = min(dist[k], d[k][i][j]);
      }
    }
  }
  int res = min(min(dist[0] + dist[1], dist[1] + dist[2]), dist[2] + dist[0]);
  for (int i = (0); i < (n); ++i) {
    for (int j = (0); j < (m); ++j) {
      if (v[i][j] == '#') {
        continue;
      }
      res =
          min(res, d[0][i][j] + d[1][i][j] + d[2][i][j] - 2 * (v[i][j] == '.'));
    }
  }
  if (res >= 5000000 - 1) {
    cout << -1;
    return 0;
  }
  cout << res;
}
