#include <bits/stdc++.h>
using namespace std;
long long n, m;
long long mp[1005][1005];
long long dis[1005][1005][5];
long long dx[4] = {1, -1, 0, 0};
long long dy[4] = {0, 0, 1, -1};
struct F {
  long long x;
  long long y;
} st, t, tt;
deque<F> q;
long long bx[5], by[5];
void bfs(long long x) {
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      if (mp[i][j] == x) {
        t.x = i;
        t.y = j;
        q.push_back(t);
      } else {
        dis[i][j][x] = 2147483647;
      }
    }
  }
  while (!q.empty()) {
    t = q.front();
    q.pop_front();
    for (long long i = 0; i < 4; i++) {
      tt.x = t.x + dx[i];
      tt.y = t.y + dy[i];
      if (tt.x >= 1 && tt.x <= n && tt.y >= 1 && tt.y <= m &&
          mp[tt.x][tt.y] != -1 && dis[tt.x][tt.y][x] == 2147483647) {
        dis[tt.x][tt.y][x] = dis[t.x][t.y][x] + (mp[tt.x][tt.y] == 0);
        if (mp[tt.x][tt.y] == 0)
          q.push_back(tt);
        else
          q.push_front(tt);
      }
    }
  }
}
int main() {
  long long i, j;
  char c;
  cin >> n >> m;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      cin >> c;
      if (c == '.')
        mp[i][j] = 0;
      else if (c == '#')
        mp[i][j] = -1;
      else
        mp[i][j] = c - '0';
    }
  }
  for (i = 1; i <= 3; i++) bfs(i);
  long long ans = 2147483647;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      ans =
          min(dis[i][j][1] + dis[i][j][2] + dis[i][j][3] - 2 * (mp[i][j] == 0),
              ans);
    }
  }
  if (ans == 2147483647)
    cout << "-1" << endl;
  else
    cout << ans;
  return 0;
}
