#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1002][1002];
int d[1002][1002][3];
vector<pair<int, int> > q;
void go(int x1, int y1, int x2, int y2, int p) {
  if (x2 < 1 || x2 > n || y2 < 1 || y2 > m || a[x2][y2] == -1) return;
  int len = 0;
  if (a[x2][y2] == 0) len = 1;
  if (d[x2][y2][p] > d[x1][y1][p] + len) {
    d[x2][y2][p] = d[x1][y1][p] + len;
    q.push_back({x2, y2});
  }
}
void bfs(int p) {
  int l = 0;
  while (l < q.size()) {
    int x = q[l].first;
    int y = q[l].second;
    go(x, y, x - 1, y, p);
    go(x, y, x + 1, y, p);
    go(x, y, x, y - 1, p);
    go(x, y, x, y + 1, p);
    l++;
    if (l > 10000000) return;
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    string s;
    cin >> s;
    for (int j = 1; j <= m; j++) {
      if (s[j - 1] == '1')
        a[i][j] = 1;
      else if (s[j - 1] == '2')
        a[i][j] = 2;
      else if (s[j - 1] == '3')
        a[i][j] = 3;
      else if (s[j - 1] == '#')
        a[i][j] = -1;
    }
  }
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      for (int x = 0; x < 3; x++) d[i][j][x] = 1e8;
    }
  for (int x = 1; x <= 3; x++) {
    q.clear();
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        if (a[i][j] == x) {
          d[i][j][a[i][j] - 1] = 0;
          q.push_back({i, j});
        }
      }
    bfs(x - 1);
  }
  int ans = 1e8;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      int l = d[i][j][0] + d[i][j][1] + d[i][j][2];
      if (a[i][j] == 0) l -= 2;
      ans = min(ans, l);
    }
  if (ans == 1e8) ans = -1;
  cout << ans << endl;
}
