#include <bits/stdc++.h>
using namespace std;
void doit(int& a, int b) {
  if (a == -1)
    a = b;
  else
    a = min(a, b);
}
vector<vector<int>> getCost(vector<vector<int>> A, int idx) {
  int n = A.size();
  int m = A[0].size();
  vector<vector<int>> D(n, vector<int>(m, -1));
  vector<vector<int>> V(n, vector<int>(m, 0));
  deque<pair<int, int>> q;
  for (int i = 0; i < n; i++) {
    for (int k = 0; k < m; k++) {
      if (A[i][k] == idx) {
        D[i][k] = 0;
        q.push_back(make_pair(i, k));
      }
    }
  }
  while (!q.empty()) {
    int r = q.front().first;
    int c = q.front().second;
    q.pop_front();
    if (V[r][c]) {
      continue;
    }
    V[r][c] = true;
    int dr[4] = {0, 1, 0, -1};
    int dc[4] = {1, 0, -1, 0};
    for (int d = 0; d < 4; d++) {
      int tr = r + dr[d];
      int tc = c + dc[d];
      if (tr < 0 || tc < 0 || tr >= n || tc >= m) {
        continue;
      }
      if (A[tr][tc] == 0) {
        continue;
      }
      if (A[r][c] == 4) {
        doit(D[tr][tc], D[r][c] + 1);
        q.push_back(make_pair(tr, tc));
      } else {
        doit(D[tr][tc], D[r][c]);
        q.push_front(make_pair(tr, tc));
      }
    }
  }
  return D;
}
int main() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> A;
  for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    vector<int> vec;
    for (int i = 0; i < m; i++) {
      int temp = 0;
      if (s[i] == '#') {
        temp = 0;
      } else if (s[i] == '.') {
        temp = 4;
      } else {
        temp = (s[i] - '0');
      }
      vec.push_back(temp);
    }
    A.push_back(vec);
  }
  vector<vector<int>> DS[3];
  for (int i = 0; i < 3; i++) {
    DS[i] = getCost(A, i + 1);
  }
  int res = -1;
  for (int i = 0; i < n; i++) {
    for (int k = 0; k < m; k++) {
      bool ok = true;
      int cost = (A[i][k] == 4 ? 1 : 0);
      for (int j = 0; j < 3; j++) {
        int temp = DS[j][i][k];
        if (temp == -1) {
          ok = false;
        }
        cost += temp;
      }
      if (ok) {
        doit(res, cost);
      }
    }
  }
  cout << res << endl;
}
