#include <bits/stdc++.h>
using namespace std;
const int INF = 1e6;
signed main() {
  int n, m;
  cin >> n >> m;
  vector<vector<vector<int>>> d(n, vector<vector<int>>(m, vector<int>(3)));
  vector<int> x = {-1, 1, 0, 0}, y = {0, 0, -1, 1};
  deque<pair<int, int>> q;
  vector<vector<char>> a(n, vector<char>(m));
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) cin >> a[i][j];
  for (int s = 0; s < 3; ++s) {
    char c = 48 + s + 1;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        if (a[i][j] == c) q.push_back({i, j});
        if (a[i][j] != c) d[i][j][s] = INF;
      }
    }
    while (q.size() > 0) {
      auto u = q.front();
      q.pop_front();
      for (int kk = 0; kk < 4; ++kk) {
        int i = u.first + x[kk], j = u.second + y[kk];
        if (i >= 0 && j >= 0 && i < n && j < m && a[i][j] != '#' &&
            d[i][j][s] == INF) {
          d[i][j][s] = d[u.first][u.second][s] + (a[i][j] == '.');
          if (a[i][j] == '.')
            q.push_back({i, j});
          else
            q.push_front({i, j});
        }
      }
    }
  }
  int dd = INF;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      dd = min(d[i][j][0] + d[i][j][1] + d[i][j][2] - 2 * (a[i][j] == '.'), dd);
  if (dd < INF)
    cout << dd;
  else
    cout << -1;
}
