#include <bits/stdc++.h>
using namespace std;
const int N = 3e7 + 10;
const int mod = 1e9 + 7;
char s[1010][1010];
int n, m;
int dis[1010][1010][4];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void bfs(int x) {
  queue<pair<long long, long long> > q;
  int i, j;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      if (s[i][j] == '0' + x) {
        q.push({i, j});
        dis[i][j][x] = 0;
      }
    }
  }
  while (q.size()) {
    auto t = q.front();
    q.pop();
    int i;
    for (i = 0; i < 4; i++) {
      int a = t.first + dx[i];
      int b = t.second + dy[i];
      if (a >= 1 && a <= n && b >= 1 && b <= m) {
        if (s[a][b] == '#') continue;
        int v = (s[a][b] == '.');
        if (dis[a][b][x] > dis[t.first][t.second][x] + v) {
          dis[a][b][x] = dis[t.first][t.second][x] + v;
          q.push({a, b});
        }
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  int i, j;
  memset(dis, 0x3f, sizeof dis);
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) cin >> s[i][j];
  }
  bfs(1);
  bfs(2);
  bfs(3);
  long long ans = 1e18;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      if (s[i][j] == '#') continue;
      long long tmp = 0;
      for (int k = 1; k <= 3; k++) {
        tmp += dis[i][j][k];
      }
      if (s[i][j] == '.') tmp -= 2;
      ans = min(ans, tmp);
    }
  }
  if (ans > 1e9) {
    cout << -1 << endl;
  } else
    cout << ans << endl;
  return 0;
}
