#include <bits/stdc++.h>
using namespace std;
const int maxi = 1000 + 3;
const int inf = 100000000 + 7;
int n, m, ans = inf;
int dis[maxi][maxi][3];
int dis_comp[maxi][maxi];
string table[maxi];
vector<pair<int, int> > comp[3];
pair<int, int> Q[maxi * maxi];
int L, R;
int dx[] = {-1, 0, 0, +1};
int dy[] = {0, -1, +1, 0};
bool isval(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; }
void bfs(int v) {
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) dis[i][j][v] = inf;
  for (int i = 0; i < comp[v].size(); i++) {
    dis[comp[v][i].first][comp[v][i].second][v] = 0;
    Q[R++] = comp[v][i];
  }
  while (L < R) {
    int x = Q[L].first;
    int y = Q[L++].second;
    for (int k = 0; k < 4; k++)
      if (isval(x + dx[k], y + dy[k]) && table[x + dx[k]][y + dy[k]] != '#' &&
          1 + dis[x][y][v] < dis[x + dx[k]][y + dy[k]][v]) {
        dis[x + dx[k]][y + dy[k]][v] = 1 + dis[x][y][v];
        Q[R++] = {x + dx[k], y + dy[k]};
      }
  }
  L = R = 0;
  memset(Q, 0, sizeof Q);
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin >> table[i];
    for (int j = 0; j < m; j++) {
      if ('1' <= table[i][j] && table[i][j] <= '3') {
        comp[table[i][j] - '1'].push_back({i, j});
      }
    }
  }
  for (int i = 0; i < 3; i++) {
    bfs(i);
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      ans = min(ans, dis[i][j][0] + dis[i][j][1] + dis[i][j][2] - 2);
    }
  }
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      dis_comp[i][j] = inf;
    }
  }
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      for (int k = 0; k < comp[i].size(); k++) {
        dis_comp[i][j] =
            min(dis_comp[i][j], dis[comp[i][k].first][comp[i][k].second][j]);
      }
    }
  }
  for (int i = 0; i < 3; i++) {
    ans = min(ans, dis_comp[(i + 2) % 3][i] + dis_comp[(i + 1) % 3][i] - 2);
  }
  if (ans >= maxi * maxi) {
    cout << -1;
  } else {
    cout << ans;
  }
}
