#include <bits/stdc++.h>
using namespace std;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
int n, m;
char a[1010][1010];
int d1[1010][1010], d2[1010][1010], d3[1010][1010];
vector<pair<int, int> > s1, s2, s3;
int ans = 0x3f3f3f3f;
int ax, ay;
void bfs(int d[1010][1010], char id) {
  queue<pair<int, int> > qq;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] == id) d[i][j] = 0, qq.push(make_pair(i, j));
  while (!qq.empty()) {
    pair<int, int> from = qq.front();
    int x = from.first, y = from.second;
    qq.pop();
    for (int i = 0; i < 4; i++) {
      int tx = x + dx[i], ty = y + dy[i];
      int dis = d[x][y] + (a[tx][ty] == '.');
      if ((d[tx][ty] != 0x3f3f3f3f && d[tx][ty] <= dis) || a[tx][ty] == '#')
        continue;
      d[tx][ty] = dis;
      qq.push(make_pair(tx, ty));
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) cin >> a[i][j];
  for (int i = 0; i <= n + 1; i++) a[i][0] = a[i][m + 1] = '#';
  for (int j = 1; j <= m; j++) a[0][j] = a[n + 1][j] = '#';
  memset(d1, 0x3f, sizeof(d1));
  memset(d2, 0x3f, sizeof(d2));
  memset(d3, 0x3f, sizeof(d3));
  bfs(d1, '1');
  bfs(d2, '2');
  bfs(d3, '3');
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (d1[i][j] != 0x3f3f3f3f && d2[i][j] != 0x3f3f3f3f &&
          d3[i][j] != 0x3f3f3f3f) {
        int calc;
        if (a[i][j] == '.') {
          calc = d1[i][j] + d2[i][j] + d3[i][j] - 2;
          if (ans > calc) ans = calc, ax = i, ay = j;
        } else if (isdigit(a[i][j])) {
          calc = d1[i][j] + d2[i][j] + d3[i][j];
          if (ans > calc) ans = calc, ax = i, ay = j;
        }
      }
  cout << (ans == 0x3f3f3f3f ? -1 : ans) << endl;
  return 0;
}
