#include <bits/stdc++.h>
using namespace std;
const int N = 1005, dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
char a[N][N];
int n, m, d[3][N][N];
void bfs(int x) {
  queue<pair<int, int> > q;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) {
      d[x][i][j] = 1e8;
      if (a[i][j] - '1' == x) {
        q.push(make_pair(i, j));
        d[x][i][j] = 0;
      }
    }
  while (!q.empty()) {
    pair<int, int> e = q.front();
    int sx = e.first, sy = e.second;
    q.pop();
    for (int i = 0; i < 4; ++i) {
      int tx = sx + dx[i], ty = sy + dy[i];
      if (tx >= 0 && tx < n && ty >= 0 && ty < m && d[x][tx][ty] > 1e7) {
        if (a[tx][ty] != '#') {
          q.push(make_pair(tx, ty));
          d[x][tx][ty] = d[x][sx][sy] + 1;
        }
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; ++i) scanf("%s", a[i]);
  for (int i = 0; i < 3; ++i) bfs(i);
  int ans = 1e8;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) {
      if (a[i][j] != '.') continue;
      int res = 0;
      for (int k = 0; k < 3; ++k) res += max(0, d[k][i][j] - 1);
      ans = min(ans, res + 1);
    }
  for (int k = 0; k < 3; ++k) {
    int x = 1e9, y = 1e9;
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j) {
        if (a[i][j] - '1' != k) continue;
        x = min(x, d[(k + 1) % 3][i][j]);
        y = min(y, d[(k + 2) % 3][i][j]);
      }
    ans = min(ans, x + y - 2);
  }
  if (ans > 1e7)
    puts("-1");
  else
    printf("%d\n", ans);
  return 0;
}
