#include <bits/stdc++.h>
using namespace std;
const int N = 1e7 + 5;
const int M = 505;
const int nmax = 1e3 + 5;
const long long inf = 1e9;
const int mod = 1e9 + 7;
const long long P = 31;
const int K = 20;
const long double eps = 1e-9;
int n, m;
string a[nmax];
int d[3][nmax][nmax];
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
int ok(int first, int second) {
  return (first >= 0 && first < n && second >= 0 && second < m &&
          a[first][second] != '#');
}
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 0; i < n; ++i) cin >> a[i];
  for (int k = 0; k < 3; ++k) {
    deque<pair<int, int> > dq;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        d[k][i][j] = N;
        if (a[i][j] == k + '1') {
          d[k][i][j] = 0;
          dq.push_back(make_pair(i, j));
        }
      }
    }
    while (!dq.empty()) {
      int first = dq.front().first;
      int second = dq.front().second;
      dq.pop_front();
      for (int i = 0; i < 4; ++i) {
        int nx = first + dx[i];
        int ny = second + dy[i];
        if (ok(nx, ny)) {
          int dist = d[k][first][second] + (a[nx][ny] == '.');
          if (dist < d[k][nx][ny]) {
            d[k][nx][ny] = dist;
            if (a[nx][ny] == '.')
              dq.push_back(make_pair(nx, ny));
            else
              dq.push_front(make_pair(nx, ny));
          }
        }
      }
    }
  }
  int ans = N;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      int sum = 0;
      for (int k = 0; k < 3; ++k) sum += d[k][i][j];
      sum -= 2 * (a[i][j] == '.');
      ans = min(ans, sum);
    }
  }
  cout << (ans >= N ? -1 : ans) << '\n';
  return 0;
}
