#include <bits/stdc++.h>
using namespace std;
long long p4[] = {-1, 1, 0, 0};
long long q4[] = {0, 0, 1, -1};
long long R, C, dis[3][1002][1002];
string s[1002], s2;
void bfs() {
  for (long long k = '1'; k <= '3'; k++) {
    deque<pair<long long, long long>> qu;
    long long fg = 0, d = k - '1';
    for (long long i = 1; i <= R; i++) {
      for (long long j = 1; j <= C; j++) {
        if (s[i][j] == k) {
          qu.push_back({i, j});
          dis[d][i][j] = 0;
          fg = 1;
          break;
        }
      }
      if (fg) break;
    }
    while (!qu.empty()) {
      long long r = qu.front().first;
      long long c = qu.front().second;
      qu.pop_front();
      for (long long i = 0; i < 4; i++) {
        long long nr = r + p4[i];
        long long nc = c + q4[i];
        if (nr >= 1 && nr <= R && nc >= 1 && nc <= C && s[nr][nc] != '#' &&
            (dis[d][r][c] + (s[nr][nc] == '.')) < dis[d][nr][nc]) {
          dis[d][nr][nc] = dis[d][r][c] + (s[nr][nc] == '.');
          if (s[nr][nc] == '.') {
            qu.push_back({nr, nc});
          } else {
            qu.push_front({nr, nc});
          }
        }
      }
    }
  }
}
int main() {
  long long i, j, k, p, q;
  cin >> R >> C;
  for (i = 1; i <= R; i++) {
    cin >> s2;
    s[i] = "*" + s2;
  }
  for (k = 0; k < 3; k++) {
    for (i = 1; i <= R; i++) {
      for (j = 1; j <= C; j++) {
        dis[k][i][j] = INT_MAX;
      }
    }
  }
  bfs();
  long long fg = 0, sm = INT_MAX;
  for (i = 1; i <= R; i++) {
    for (j = 1; j <= C; j++) {
      if (s[i][j] >= '1' && s[i][j] <= '3') {
        if (dis[0][i][j] == INT_MAX || dis[1][i][j] == INT_MAX ||
            dis[2][i][j] == INT_MAX) {
          fg = 1;
          break;
        } else {
          p = dis[0][i][j] + dis[1][i][j] + dis[2][i][j];
          sm = min(p, sm);
        }
      } else if (s[i][j] == '.') {
        if (dis[0][i][j] != INT_MAX && dis[1][i][j] != INT_MAX &&
            dis[2][i][j] != INT_MAX) {
          p = dis[0][i][j] + dis[1][i][j] + dis[2][i][j] - 2;
          sm = min(p, sm);
        }
      }
    }
    if (fg) break;
  }
  if (fg) sm = -1;
  cout << sm << endl;
  return 0;
}
