#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
int d[4][2] = {1, 0, 0, 1, 0, -1, -1, 0};
char g[maxn][maxn];
int dist[4][maxn][maxn];
int n, m;
void bfs(int t) {
  queue<pair<int, int> > q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (g[i][j] == t + '0') q.push(pair<int, int>(i, j)), dist[t][i][j] = 0;
    }
  }
  while (!q.empty()) {
    pair<int, int> temp = q.front();
    q.pop();
    int x = temp.first, y = temp.second;
    for (int i = 0; i < 4; i++) {
      int xx = x + d[i][0];
      int yy = y + d[i][1];
      int res = 0;
      if (xx < 1 || xx > n || yy < 1 || yy > m || g[xx][yy] == '#') continue;
      if (g[xx][yy] == '.') res = 1;
      if (dist[t][xx][yy] > dist[t][x][y] + res) {
        dist[t][xx][yy] = dist[t][x][y] + res;
        q.push(pair<int, int>(xx, yy));
      }
    }
  }
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) scanf("%s", g[i] + 1);
  memset(dist, 0x3f, sizeof dist);
  for (int i = 1; i <= 3; i++) bfs(i);
  long long ans = 0x3f3f3f3f, res;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      res = 0;
      for (int k = 1; k <= 3; k++) res += dist[k][i][j];
      if (g[i][j] == '.') res -= 2;
      ans = min(res, ans);
    }
  }
  ans >= 0x3f3f3f3f ? puts("-1") : printf("%lld\n", ans);
  return 0;
}
