#include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f;
const int Inf = 0x3f3f3f3f;
const int p = 107;
const int P = 100007;
const int Mod = 1e9 + 7;
const long double eps = 1e-14;
int n, m;
char c[1005][1005];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int ans = Inf;
int vis[1005][1005];
queue<pair<int, int> > Q;
void dfs(int x, int y, int dis, int D[1005][1005]) {
  for (int k = 0; k < 4; k++) {
    int nx = x + dx[k], ny = y + dy[k];
    if (nx < 1 || ny < 1 || nx > n || ny > m || vis[nx][ny] == 1 ||
        c[nx][ny] == '#')
      continue;
    int tmp = (c[nx][ny] == '.' ? 1 : 0);
    D[nx][ny] = dis + tmp;
    vis[nx][ny] = 1;
    if (tmp == 1) continue;
    dfs(nx, ny, dis, D);
  }
}
void bfs(int D[1005][1005], int id) {
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) D[i][j] = -1, vis[i][j] = 0;
  while (!Q.empty()) Q.pop();
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (c[i][j] == id + '0') {
        Q.push(make_pair(i, j));
        D[i][j] = 0;
        vis[i][j] = 1;
      }
    }
  }
  while (!Q.empty()) {
    pair<int, int> t = Q.front();
    Q.pop();
    int x = t.first, y = t.second;
    for (int k = 0; k < 4; k++) {
      int nx = x + dx[k], ny = y + dy[k];
      if (nx < 1 || ny < 1 || nx > n || ny > m || c[nx][ny] == '#' ||
          vis[nx][ny])
        continue;
      int tmp = (c[nx][ny] == '.' ? 1 : 0);
      D[nx][ny] = D[x][y] + tmp;
      Q.push(make_pair(nx, ny));
      vis[nx][ny] = 1;
      if (tmp == 1) continue;
      dfs(nx, ny, D[x][y], D);
    }
  }
}
int dis1[1005][1005], dis2[1005][1005], dis3[1005][1005];
void work() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> c[i][j];
    }
  }
  bfs(dis1, 1);
  bfs(dis2, 2);
  bfs(dis3, 3);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (c[i][j] == '#') continue;
      if (dis1[i][j] == -1 || dis2[i][j] == -1 || dis3[i][j] == -1) continue;
      int cst = dis1[i][j] + dis2[i][j] + dis3[i][j];
      if (c[i][j] == '.') {
        cst -= 2;
      }
      ans = min(ans, cst);
    }
  }
  cout << (ans == Inf ? -1 : ans) << endl;
}
signed main() {
  int T = 1;
  while (T--) {
    work();
  }
  return 0;
}
