#include <bits/stdc++.h>
using namespace std;
int n, m, p, l, y[] = {1, 2, 0}, d[3][1005][1005],
                r[] = {9000005, 9000005, 9000005, 9000005},
                k[] = {0, 0, 1, -1, 0, 0};
char x[1005][1005];
queue<int> q, w;
int main() {
  scanf("%d%d", &n, &m);
  for (int a = 0; a < n; a++) scanf("%s", x[a]);
  for (int c = 0; c < 3; c++) {
    for (int a = 0; a < n; a++)
      for (int b = 0; b < m; b++)
        if (x[a][b] == 49 + c) {
          q.push(a);
          w.push(b);
          d[c][a][b] = 1;
        }
    while (!q.empty()) {
      for (int a = 0; a < 4; a++) {
        p = q.front() + k[a];
        l = w.front() + k[a + 2];
        if (p >= 0 && p < n && l >= 0 && l < m && !d[c][p][l] &&
            x[p][l] != 35) {
          if (x[p][l] == 49 + y[c] && x[q.front()][w.front()] == 49 + c)
            r[c] = 0;
          if (x[p][l] == 46) {
            d[c][p][l] = d[c][q.front()][w.front()] + 1;
            q.push(p);
            w.push(l);
          }
        }
      }
      q.pop();
      w.pop();
    }
  }
  for (int a = 0; a < n; a++)
    for (int b = 0; b < m; b++) {
      for (int c = 0; c < 3; c++)
        if (d[c][a][b] && d[y[c]][a][b])
          r[c] = min(r[c], d[c][a][b] + d[y[c]][a][b] - 2 - 1);
      if (d[0][a][b] && d[1][a][b] && d[2][a][b])
        r[3] = min(r[3], d[0][a][b] + d[1][a][b] + d[2][a][b] - 3 - 2);
    }
  for (int a = 0; a < 3; a++)
    if (r[a] != 9000005 && r[y[a]] != 9000005) r[3] = min(r[3], r[a] + r[y[a]]);
  printf("%d\n", r[3] == 9000005 ? -1 : r[3]);
  return 0;
}
