#include <bits/stdc++.h>
using namespace std;
const int M = 1e3 + 10;
char mmp[M][M];
int n, m, dr[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int dis[4][M][M], de[4][4];
struct TnT {
  int x, y;
  TnT() {}
  TnT(int x, int y) : x(x), y(y) {}
};
void bfs(int num) {
  queue<TnT> q;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (mmp[i][j] == num + '0') {
        q.push(TnT(i, j));
        dis[num][i][j] = 0;
      }
    }
  }
  while (!q.empty()) {
    TnT gg = q.front();
    q.pop();
    char cp = mmp[gg.x][gg.y];
    if (cp != '.') {
      de[num][cp - '0'] = min(dis[num][gg.x][gg.y] - 1, de[num][cp - '0']);
    }
    for (int i = 0; i < 4; i++) {
      TnT gl = gg;
      gl.x += dr[i][0], gl.y += dr[i][1];
      if (gl.x >= 0 && gl.x < n && gl.y >= 0 && gl.y < m &&
          mmp[gl.x][gl.y] != '#') {
        if (dis[num][gl.x][gl.y] == 0X3f3f3f3f) {
          dis[num][gl.x][gl.y] = dis[num][gg.x][gg.y] + 1;
          q.push(gl);
        }
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin >> mmp[i];
  }
  memset(dis, 0X3f3f3f3f, sizeof(dis));
  memset(de, 0X3f3f3f3f, sizeof(de));
  for (int i = 1; i <= 3; i++) {
    bfs(i);
  }
  int ans = de[1][2] + de[1][3];
  ans = min(de[1][2] + de[2][3], ans);
  ans = min(de[1][3] + de[2][3], ans);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (mmp[i][j] != '.') continue;
      if (dis[1][i][j] == 0X3f3f3f3f || dis[2][i][j] == 0X3f3f3f3f ||
          dis[3][i][j] == 0X3f3f3f3f)
        continue;
      ans = min(dis[1][i][j] + dis[2][i][j] + dis[3][i][j] - 2, ans);
    }
  }
  if (ans >= 0X3f3f3f3f)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
