#include <bits/stdc++.h>
using namespace std;
template <typename T>
T abs(T x) {
  return x > 0 ? x : -x;
}
template <typename T>
T sqr(T x) {
  return x * x;
}
int d[3][1005][1005];
string s[1005];
bool used[3][1005][1005];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int n, m;
void bfs(int ind, char c) {
  priority_queue<pair<int, pair<int, int> > > q;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (s[i][j] == c) {
        q.push(make_pair(0, make_pair(i, j)));
        d[ind][i][j] = 0;
        used[ind][i][j] = 1;
      }
    }
  while (!q.empty()) {
    int cx = q.top().second.first;
    int cy = q.top().second.second;
    used[ind][cx][cy] = 1;
    int cd = -q.top().first;
    q.pop();
    if (cd > d[ind][cx][cy]) continue;
    for (int i = 0; i < 4; i++) {
      int nx = cx + dx[i];
      int ny = cy + dy[i];
      if (nx >= 0 && ny >= 0 && nx < n && ny < m && s[nx][ny] != '#') {
        if (d[ind][nx][ny] > d[ind][cx][cy] + (s[nx][ny] == '.')) {
          d[ind][nx][ny] = d[ind][cx][cy] + (s[nx][ny] == '.');
          q.push(make_pair(-(d[ind][cx][cy] + (s[nx][ny] == '.')),
                           make_pair(nx, ny)));
        }
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin >> s[i];
  }
  int inf = 1000000;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      for (int h = 0; h < 3; h++) d[h][i][j] = inf;
  bfs(0, '1');
  bfs(1, '2');
  bfs(2, '3');
  int ans = inf + 5;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      if (s[i][j] == '#') continue;
      bool u = 1;
      for (int h = 0; h < 3; h++) u &= used[h][i][j];
      if (!u) continue;
      int sum = 0;
      for (int h = 0; h < 3; h++) sum += d[h][i][j];
      ans = min(ans, (s[i][j] == '.' ? sum - 2 : sum));
    }
  if (ans >= inf) {
    puts("-1");
  } else {
    cout << ans << "\n";
  }
  return 0;
}
