#include <bits/stdc++.h>
using namespace std;
char a[1001][1001];
int d[3][1001][1001];
class comp {
 public:
  bool operator()(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {
    return a.second > b.second;
  }
};
int n, m;
bool valid(int x, int y) {
  if (x < 0 or x >= n or y < 0 or y >= m) return 0;
  if (a[x][y] == '#') return 0;
  return 1;
}
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
void dj(int second,
        priority_queue<pair<pair<int, int>, int>,
                       vector<pair<pair<int, int>, int> >, comp>& pq) {
  pair<pair<int, int>, int> u;
  int x, y, dis;
  while (pq.size()) {
    u = pq.top();
    pq.pop();
    x = u.first.first;
    y = u.first.second;
    dis = u.second;
    if (dis >= d[second][x][y]) continue;
    d[second][x][y] = dis;
    for (int k = 0; k < 4; k++) {
      if (valid(x + dx[k], y + dy[k]) and
          d[second][x + dx[k]][y + dy[k]] >
              d[second][x][y] + (int)(a[x + dx[k]][y + dy[k]] == '.')) {
        pq.push(make_pair(make_pair(x + dx[k], y + dy[k]),
                          dis + (int)(a[x + dx[k]][y + dy[k]] == '.')));
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  for (int k = 0; k < 3; k++) {
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) d[k][i][j] = 3 * n * m;
  }
  priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int> >,
                 comp>
      d1, d2, d3;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      if (a[i][j] == '1') {
        d1.push(make_pair(make_pair(i, j), 0));
      } else if (a[i][j] == '2') {
        d2.push(make_pair(make_pair(i, j), 0));
      } else if (a[i][j] == '3') {
        d3.push(make_pair(make_pair(i, j), 0));
      }
    }
  dj(0, d1);
  dj(1, d2);
  dj(2, d3);
  int d12 = 3 * n * m;
  int d13 = 3 * n * m;
  int d23 = 3 * n * m;
  int d123 = d12;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] != '#') {
        if (d[0][i][j] != 3 * n * m and d[1][i][j] != 3 * n * m)
          d12 = min(d12, d[0][i][j] + d[1][i][j] - (int)(a[i][j] == '.'));
        if (d[0][i][j] != 3 * n * m and d[2][i][j] != 3 * n * m)
          d13 = min(d13, d[0][i][j] + d[2][i][j] - (int)(a[i][j] == '.'));
        if (d[1][i][j] != 3 * n * m and d[2][i][j] != 3 * n * m)
          d23 = min(d23, d[1][i][j] + d[2][i][j] - (int)(a[i][j] == '.'));
        if (d[0][i][j] != 3 * n * m and d[1][i][j] != 3 * n * m and
            d[2][i][j] != 3 * n * m)
          d123 = min(d123, d[0][i][j] + d[1][i][j] + d[2][i][j] -
                               2 * (int)(a[i][j] == '.'));
      }
    }
  }
  int ans = d123;
  ans = min(d12 + d13, ans);
  ans = min(ans, d12 + d23);
  ans = min(ans, d13 + d23);
  if (ans >= 3 * n * m) ans = -1;
  cout << ans;
}
