#include <bits/stdc++.h>
using namespace std;
const int MX = 1000 + 5;
const int INF = 0x3f3f3f3f;
int n, m;
int d[3][MX][MX], dp[10][10];
char S[MX][MX];
int dist[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
void build(int s) {
  queue<pair<int, int> > Q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (S[i][j] == '1' + s) {
        d[s][i][j] = 0;
        Q.push(pair<int, int>(i, j));
      } else
        d[s][i][j] = INF;
    }
  }
  for (int i = 0; i <= 2; i++) {
    dp[s][i] = INF;
  }
  while (!Q.empty()) {
    pair<int, int> f = Q.front();
    Q.pop();
    int x = f.first, y = f.second;
    if ('1' <= S[x][y] && S[x][y] <= '3') {
      dp[s][S[x][y] - '1'] = min(dp[s][S[x][y] - '1'], d[s][x][y] - 1);
    }
    for (int k = 0; k < 4; k++) {
      int nx = x + dist[k][0], ny = y + dist[k][1];
      if (nx < 1 || nx > n || ny < 1 || ny > m || S[nx][ny] == '#') continue;
      if (d[s][nx][ny] == INF) {
        d[s][nx][ny] = d[s][x][y] + 1;
        Q.push(pair<int, int>(nx, ny));
      }
    }
  }
}
int main() {
  while (~scanf("%d%d", &n, &m)) {
    for (int i = 1; i <= n; i++) {
      scanf("%s", S[i] + 1);
    }
    for (int i = 1; i <= 3; i++) {
      build(i - 1);
    }
    int ans = INF;
    ans = min(ans, dp[0][1] + dp[0][2]);
    ans = min(ans, dp[1][0] + dp[1][2]);
    ans = min(ans, dp[2][0] + dp[2][1]);
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        if (d[0][i][j] == INF || d[1][i][j] == INF || d[2][i][j] == INF)
          continue;
        ans = min(ans, d[0][i][j] + d[1][i][j] + d[2][i][j] - 2);
      }
    }
    printf("%d\n", ans == INF ? -1 : ans);
  }
  return 0;
}
