#include <bits/stdc++.h>
using namespace std;
char str[1003][1003];
int dis[3][1003][1003], n, m;
int dirx[] = {0, 0, 1, -1};
int diry[] = {1, -1, 0, 0};
queue<pair<int, int> > q;
void bfs(int p) {
  while (!q.empty()) {
    int x = q.front().first;
    int y = q.front().second;
    q.pop();
    for (int i = 0; i < 4; i++) {
      int a = x + dirx[i];
      int b = y + diry[i];
      if (a < 0 || a > n - 1 || b < 0 || b > m - 1 || str[a][b] == '#' ||
          dis[p][a][b] != 100000000)
        continue;
      dis[p][a][b] = dis[p][x][y] + 1;
      q.push({a, b});
    }
  }
  return;
}
int main() {
  int res = 100000000;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%s", str[i]);
    for (int j = 0; j < m; j++) {
      dis[0][i][j] = 100000000;
      if (str[i][j] == '1') dis[0][i][j] = 0, q.push({i, j});
    }
  }
  bfs(0);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      dis[1][i][j] = 100000000;
      if (str[i][j] == '2') dis[1][i][j] = 0, q.push({i, j});
    }
  }
  bfs(1);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      dis[2][i][j] = 100000000;
      if (str[i][j] == '3') dis[2][i][j] = 0, q.push({i, j});
    }
  }
  bfs(2);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      res = min(res, dis[0][i][j] + dis[1][i][j] + dis[2][i][j] - 2);
  int x = 100000000, y = 100000000;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (str[i][j] == '1') x = min(x, dis[1][i][j]), y = min(y, dis[2][i][j]);
  res = min(res, x + y - 2);
  x = 100000000, y = 100000000;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (str[i][j] == '2') x = min(x, dis[0][i][j]), y = min(y, dis[2][i][j]);
  res = min(res, x + y - 2);
  x = 100000000, y = 100000000;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (str[i][j] == '3') x = min(x, dis[1][i][j]), y = min(y, dis[0][i][j]);
  res = min(res, x + y - 2);
  if (res > (n * m)) res = -1;
  printf("%d\n", res);
  return 0;
}
