#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-10;
const int M = 1e9 + 7;
int n, m;
char s[N][N];
int dis[N][N][3];
int ft[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
queue<pair<int, int> > q;
void add(char c, int deep, int nt) {
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (s[i][j] == c) {
        dis[i][j][nt] = deep;
        q.push(make_pair(i, j));
      }
}
void bfs(int nt) {
  add('0' + nt, 0, nt);
  while (!q.empty()) {
    pair<int, int> u = q.front();
    q.pop();
    int d = dis[u.first][u.second][nt];
    for (int i = 0; i < 4; i++) {
      int first = u.first + ft[i][0], second = u.second + ft[i][1];
      if (first >= 0 && first < n && second >= 0 && second < m &&
          s[first][second] != '#' && dis[first][second][nt] == INF) {
        if (isdigit(s[first][second]))
          add(s[first][second], d, nt);
        else {
          dis[first][second][nt] = d + 1;
          q.push(make_pair(first, second));
        }
      }
    }
  }
}
int main() {
  memset(dis, INF, sizeof(dis));
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", s[i]);
  for (int i = 1; i <= 3; i++) bfs(i);
  long long ans = INF;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      long long tmp = 0;
      for (int k = 1; k <= 3; k++) tmp += dis[i][j][k];
      if (s[i][j] == '.')
        ans = min(ans, tmp - 2);
      else if (isdigit(s[i][j]))
        ans = min(ans, tmp);
    }
  if (ans == INF) ans = -1;
  printf("%lld\n", ans);
  return 0;
}
