#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int N = 1010;
int n, m;
string s[N];
int dp[4][N][N];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool valid(int x, int y) {
  return x >= 0 && y >= 0 && x < n && y < m && s[x][y] != '#';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> s[i];
  memset(dp, -1, sizeof(dp));
  for (int c = '1'; c <= '3'; c++) {
    deque<pair<int, int> > q;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if (s[i][j] == c) {
          dp[c - '1'][i][j] = 0;
          q.push_back(make_pair(i, j));
        }
    while (!q.empty()) {
      int x = q.front().first;
      int y = q.front().second;
      q.pop_front();
      for (int k = 0; k < 4; k++) {
        int nx = x + dx[k];
        int ny = y + dy[k];
        if (valid(nx, ny)) {
          int dist = dp[c - '1'][x][y] + (s[nx][ny] == '.');
          if (dp[c - '1'][nx][ny] == -1 || dp[c - '1'][nx][ny] > dist) {
            dp[c - '1'][nx][ny] = dist;
            if (s[nx][ny] == '.')
              q.push_back(make_pair(nx, ny));
            else
              q.push_front(make_pair(nx, ny));
          }
        }
      }
    }
  }
  int ans = -1;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (dp[0][i][j] != -1 && dp[1][i][j] != -1 && dp[2][i][j] != -1) {
        int val =
            dp[0][i][j] + dp[1][i][j] + dp[2][i][j] - 2 * (s[i][j] == '.');
        if (ans == -1 || ans > val) ans = val;
      }
  cout << ans;
  return 0;
}
