#include <bits/stdc++.h>
using namespace std;
char d[1009][1009];
int dist[1009][1009][3];
bool vis[3];
deque<pair<int, int> > q;
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%s", d[i]);
  }
  memset(dist, -1, sizeof(dist));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (d[i][j] == '#') continue;
      if (d[i][j] == '.') continue;
      int cv = d[i][j] - '1';
      if (vis[cv]) continue;
      vis[cv] = true;
      while (q.size()) q.pop_front();
      dist[i][j][cv] = 0;
      q.push_back(pair<int, int>(i, j));
      while (!q.empty()) {
        pair<int, int> cur = q.front();
        q.pop_front();
        int cy = cur.first, cx = cur.second;
        for (int k = 0; k < 4; k++) {
          int ny = cy + dy[k], nx = cx + dx[k];
          if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
            if (dist[ny][nx][cv] != -1) continue;
            if (d[ny][nx] == '#') continue;
            if (d[ny][nx] == '.') {
              dist[ny][nx][cv] = dist[cy][cx][cv] + 1;
              q.push_back(pair<int, int>(ny, nx));
              continue;
            }
            dist[ny][nx][cv] = dist[cy][cx][cv];
            q.push_front(pair<int, int>(ny, nx));
          }
        }
      }
    }
  }
  int cm = 999999999;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (d[i][j] == '#') continue;
      bool legit = true;
      for (int k = 0; k < 3; k++) {
        if (dist[i][j][k] == -1) {
          legit = false;
          break;
        }
      }
      if (!legit) continue;
      if (d[i][j] == '.') {
        int v = 0;
        for (int k = 0; k < 3; k++) {
          v += dist[i][j][k];
        }
        v -= 2;
        cm = min(cm, v);
        continue;
      }
      int v = 0;
      for (int k = 0; k < 3; k++) {
        v += dist[i][j][k];
      }
      cm = min(cm, v);
    }
  }
  if (cm < 999999999)
    printf("%d", cm);
  else
    printf("-1");
}
