#include <bits/stdc++.h>
using namespace std;
const long long nInf = -1000000000;
const long long pInf = 1000000000;
const long long mod = 1000000007;
const int MAXN = 1010;
void getdata();
void preproc();
void solve();
int dists[4][MAXN][MAXN], dist1[4][4];
int n, m;
char a[MAXN][MAXN];
void bfs(int num) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      dists[num][i][j] = pInf;
    }
  }
  queue<pair<pair<int, int>, int>> q;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] - '0' == num) {
        q.push(make_pair(make_pair(i, j), 0));
        dists[num][i][j] = 0;
      }
      if (a[i][j] == '#') dists[num][i][j] = -1;
    }
  }
  while (!q.empty()) {
    auto cur = q.front();
    q.pop();
    int x = cur.first.first;
    int y = cur.first.second;
    int dist = cur.second;
    if (x > 0 && dists[num][x - 1][y] > dist + 1) {
      dists[num][x - 1][y] = dist + 1;
      q.push(make_pair(make_pair(x - 1, y), dist + 1));
    }
    if (y > 0 && dists[num][x][y - 1] > dist + 1) {
      dists[num][x][y - 1] = dist + 1;
      q.push(make_pair(make_pair(x, y - 1), dist + 1));
    }
    if (x < n - 1 && dists[num][x + 1][y] > dist + 1) {
      dists[num][x + 1][y] = dist + 1;
      q.push(make_pair(make_pair(x + 1, y), dist + 1));
    }
    if (y < m - 1 && dists[num][x][y + 1] > dist + 1) {
      dists[num][x][y + 1] = dist + 1;
      q.push(make_pair(make_pair(x, y + 1), dist + 1));
    }
  }
}
int main() {
  int t = 1;
  for (int i = 0; i < t; i++) {
    getdata();
    preproc();
    solve();
  }
  return 0;
}
void getdata() {
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("\n");
    scanf("%s", &a[i]);
  }
}
void preproc() {
  for (int i = 1; i <= 3; i++) {
    bfs(i);
  }
}
void solve() {
  for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
      dist1[i][j] = pInf;
    }
  }
  dist1[1][2] = pInf;
  dist1[1][3] = pInf;
  dist1[2][3] = pInf;
  for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
      if (i == j) continue;
      for (int x = 0; x < n; x++) {
        for (int y = 0; y < m; y++) {
          if (a[x][y] - '0' == j && dist1[i][j] > dists[i][x][y]) {
            dist1[i][j] = dists[i][x][y];
          }
        }
      }
    }
  }
  int res1 = dist1[1][2] + dist1[2][3];
  res1 = min(res1, dist1[1][2] + dist1[1][3]);
  res1 = min(res1, dist1[1][3] + dist1[2][3]);
  if (res1 >= pInf) {
    printf("-1\n");
    return;
  }
  res1 -= 2;
  int res2 = pInf;
  for (int x = 0; x < n; x++) {
    for (int y = 0; y < m; y++) {
      if (a[x][y] == '.') {
        long long cur = 0;
        for (int i = 1; i <= 3; i++) {
          cur += dists[i][x][y];
        }
        cur -= 2;
        if (res2 > cur) res2 = cur;
      }
    }
  }
  if (res2 > res1) {
    printf("%d\n", res1);
  } else {
    printf("%d\n", res2);
  }
}
