#include <bits/stdc++.h>
using namespace std;
inline void ckmin(int &x, int y) { x = min(x, y); }
inline void ckmax(int &x, int y) { x = max(x, y); }
int T, case_;
int n, m, x, y, ans = 0x3f3f3f3f;
int dis[1010][1010][4];
char p[1010][1010];
void bfs(int col) {
  queue<pair<int, int>> q;
  for (int i = 0; i <= n - 1; i++) {
    for (int j = 0; j <= m - 1; j++) {
      if (p[i][j] - '0' == col) {
        dis[i][j][col] = 0;
        q.push(make_pair(i, j));
      }
    }
  }
  while (!q.empty()) {
    x = q.front().first;
    y = q.front().second;
    q.pop();
    if (p[x][y] == '#') {
      dis[x][y][col] = 0x3f3f3f3f;
      continue;
    }
    if (x) {
      if (dis[x - 1][y][col] > dis[x][y][col] + (p[x - 1][y] == '.')) {
        dis[x - 1][y][col] = dis[x][y][col] + (p[x - 1][y] == '.');
        q.push(make_pair(x - 1, y));
      }
    }
    if (y) {
      if (dis[x][y - 1][col] > dis[x][y][col] + (p[x][y - 1] == '.')) {
        dis[x][y - 1][col] = dis[x][y][col] + (p[x][y - 1] == '.');
        q.push(make_pair(x, y - 1));
      }
    }
    if (x != n - 1) {
      if (dis[x + 1][y][col] > dis[x][y][col] + (p[x + 1][y] == '.')) {
        dis[x + 1][y][col] = dis[x][y][col] + (p[x + 1][y] == '.');
        q.push(make_pair(x + 1, y));
      }
    }
    if (y != m - 1) {
      if (dis[x][y + 1][col] > dis[x][y][col] + (p[x][y + 1] == '.')) {
        dis[x][y + 1][col] = dis[x][y][col] + (p[x][y + 1] == '.');
        q.push(make_pair(x, y + 1));
      }
    }
  }
}
void solve() {
  cin >> n >> m;
  for (int i = 0; i <= n - 1; i++)
    for (int j = 0; j <= m - 1; j++) cin >> p[i][j];
  memset(dis, 63, sizeof(dis));
  for (int i = 1; i <= 3; i++) bfs(i);
  for (int i = 0; i <= n - 1; i++) {
    for (int j = 0; j <= m - 1; j++) {
      if (dis[i][j][1] == 0x3f3f3f3f || dis[i][j][2] == 0x3f3f3f3f ||
          dis[i][j][3] == 0x3f3f3f3f)
        continue;
      ans = min(ans, dis[i][j][1] + dis[i][j][2] + dis[i][j][3] -
                         2 * (p[i][j] == '.'));
    }
  }
  if (ans == 0x3f3f3f3f)
    cout << -1;
  else
    cout << ans;
}
int main() {
  T = 1;
  for (case_ = 1; case_ <= T; case_++) solve();
  return 0;
}
