#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
const int inf = 300100100;
int n, m;
char s[maxn][maxn];
int dst[5][maxn][maxn];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
void bfs(int x) {
  for (int i = (0); i <= (int(n) - 1); ++i)
    for (int j = (0); j <= (int(m) - 1); ++j) dst[x][i][j] = inf;
  queue<int> q;
  for (int i = (0); i <= (int(n) - 1); ++i)
    for (int j = (0); j <= (int(m) - 1); ++j)
      if (s[i][j] == '0' + x) {
        q.push(i);
        q.push(j);
        dst[x][i][j] = 0;
      }
  while (!q.empty()) {
    int a = q.front();
    q.pop();
    int b = q.front();
    q.pop();
    for (int k = (0); k <= (int(4) - 1); ++k) {
      int A = a + dx[k], B = b + dy[k];
      if (A < 0 || B < 0 || A >= n || B >= m) continue;
      if (s[A][B] == '#') continue;
      if (dst[x][A][B] > dst[x][a][b] + 1) {
        dst[x][A][B] = dst[x][a][b] + 1;
        q.push(A);
        q.push(B);
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = (0); i <= (int(n) - 1); ++i) scanf("%s", s[i]);
  for (int i = (1); i <= (3); ++i) bfs(i);
  int res = inf;
  for (int x = (1); x <= (3); ++x) {
    int c2r = 0;
    for (int y = (1); y <= (3); ++y)
      if (x != y) {
        int cd = inf;
        for (int i = (0); i <= (int(n) - 1); ++i)
          for (int j = (0); j <= (int(m) - 1); ++j)
            if (s[i][j] == '0' + y) cd = min(cd, dst[x][i][j]);
        c2r += cd - 1;
      }
    if (c2r < res) res = c2r;
  }
  for (int i = (0); i <= (int(n) - 1); ++i)
    for (int j = (0); j <= (int(m) - 1); ++j) {
      int cd = 0;
      for (int x = (1); x <= (3); ++x) cd += dst[x][i][j];
      if (cd - 2 < res) res = cd - 2;
    }
  printf("%d\n", res < inf / 2 ? res : -1);
  return 0;
}
