#include <bits/stdc++.h>
using namespace std;
int main() {
  int m, n;
  cin >> m >> n;
  vector<vector<int>> mat(m + 2, vector<int>(n + 2));
  for (int i = 1; i <= m; i++) {
    string str;
    cin >> str;
    for (int j = 0; j < n; j++)
      mat[i][j + 1] =
          ((str[j] == '.' || str[j] == '#') ? str[j] : str[j] - '0');
  }
  vector<vector<int>> dp[4];
  deque<pair<int, int>> dq[4];
  for (int it = 1; it <= 3; it++) dp[it].resize(m + 2, vector<int>(n + 2));
  const int addLin[4] = {-1, 0, 1, 0};
  const int addCol[4] = {0, 1, 0, -1};
  for (int i = 1; i <= m; i++)
    for (int j = 1; j <= n; j++)
      if (1 <= mat[i][j] && mat[i][j] <= 3)
        for (int k = 0; k < 4; k++) {
          int x = i + addLin[k];
          int y = j + addCol[k];
          if (mat[x][y] != '#') {
            dp[mat[i][j]][i][j] = 1;
            dq[mat[i][j]].push_front(make_pair(i, j));
            break;
          }
        }
  for (int it = 1; it <= 3; it++)
    while (!dq[it].empty()) {
      pair<int, int> cell = dq[it].front();
      dq[it].pop_front();
      for (int i = 0; i < 4; i++) {
        int x = cell.first + addLin[i];
        int y = cell.second + addCol[i];
        if (!dp[it][x][y] && 1 <= x && x <= m && 1 <= y && y <= n) {
          if (mat[x][y] == '.') {
            dp[it][x][y] = dp[it][cell.first][cell.second] + 1;
            dq[it].push_back(make_pair(x, y));
          } else if (1 <= mat[x][y] && mat[x][y] <= 3) {
            dp[it][x][y] = dp[it][cell.first][cell.second];
            dq[it].push_front(make_pair(x, y));
          }
        }
      }
    }
  int sol = INT_MAX;
  for (int i = 1; i <= m; i++)
    for (int j = 1; j <= n; j++)
      if (dp[1][i][j] && dp[2][i][j] && dp[3][i][j] && mat[i][j] == '.')
        sol = min(sol, dp[1][i][j] + dp[2][i][j] + dp[3][i][j]);
      else if (dp[1][i][j] == 1 && dp[2][i][j] == 1 && dp[3][i][j] == 1) {
        cout << "0\n";
        return 0;
      }
  cout << (sol == INT_MAX ? -1 : sol - 5) << '\n';
  return 0;
}
