#include <bits/stdc++.h>
using namespace std;
char in[1050][1050];
int dis[3][1050][1050];
bool chk[3][1050][1050];
priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >,
               greater<pair<int, pair<int, int> > > >
    H;
int p[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int main() {
  int n, m, i, j, k;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      dis[0][i][j] = dis[1][i][j] = dis[2][i][j] = 534567891;
  for (i = 0; i < n; i++) {
    scanf("%s", in[i]);
    for (int j = 0; j < m; j++)
      if (in[i][j] >= '1' && in[i][j] <= '3') dis[in[i][j] - '1'][i][j] = 0;
  }
  for (i = 0; i < 3; i++) {
    for (j = 0; j < n; j++)
      for (k = 0; k < m; k++)
        if (in[j][k] == i + '1') H.push(make_pair(0, pair<int, int>(j, k)));
    while (!H.empty()) {
      pair<int, pair<int, int> > u = H.top();
      H.pop();
      if (chk[i][u.second.first][u.second.second]) continue;
      chk[i][u.second.first][u.second.second] = true;
      for (int j = 0; j < 4; j++) {
        pair<int, int> u2 =
            pair<int, int>(u.second.first + p[j][0], u.second.second + p[j][1]);
        if (u2.first < 0 || u2.first >= n || u2.second < 0 || u2.second >= m ||
            in[u2.first][u2.second] == '#')
          continue;
        int d = u.first + 1;
        if (in[u.second.first][u.second.second] >= '1' &&
            in[u.second.first][u.second.second] <= '3')
          d--;
        if (dis[i][u2.first][u2.second] > d) {
          dis[i][u2.first][u2.second] = d;
          H.push(make_pair(d, u2));
        }
      }
    }
  }
  int ans = 534567891 * 3;
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++)
      ans = min(ans, dis[0][i][j] + dis[1][i][j] + dis[2][i][j] +
                         ((in[i][j] == '.') ? 1 : 0));
  if (ans >= 534567891 / 2)
    printf("-1\n");
  else
    printf("%d\n", ans);
  return 0;
}
