#include <bits/stdc++.h>
using namespace std;
int go[2][4] = {{1, -1, 0, 0}, {0, 0, 1, -1}};
char mp[1010][1010];
int n, m;
int sp[4][1010][1010], vis[1010][1010];
struct node {
  int x, y, c;
} tmp, tmp1;
void bfs(int src) {
  int i, j, xx, yy;
  deque<node> q;
  memset(vis, 0, sizeof(vis));
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      sp[src][i][j] = 1 << 29;
      if (mp[i][j] == src + '0') {
        tmp.x = i;
        tmp.y = j;
        tmp.c = 0;
        q.push_back(tmp);
        vis[i][j] = 1;
      }
    }
  }
  while (!q.empty()) {
    tmp = q.front();
    q.pop_front();
    sp[src][tmp.x][tmp.y] = tmp.c;
    for (i = 0; i < 4; i++) {
      xx = tmp.x + go[0][i];
      yy = tmp.y + go[1][i];
      if (xx < 0 || yy < 0 || xx >= n || yy >= m || mp[xx][yy] == '#' ||
          vis[xx][yy])
        continue;
      tmp1.x = xx;
      tmp1.y = yy;
      if (mp[xx][yy] == '.') {
        tmp1.c = tmp.c + 1;
        q.push_back(tmp1);
      } else {
        tmp1.c = tmp.c;
        q.push_front(tmp1);
      }
      vis[xx][yy] = 1;
    }
  }
}
int main() {
  int i, j, ans;
  while (cin >> n >> m) {
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        scanf(" %c", &mp[i][j]);
      }
    }
    bfs(1);
    bfs(2);
    bfs(3);
    ans = 1 << 29;
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        ans = min(ans, sp[1][i][j] + sp[2][i][j] + sp[3][i][j] -
                           (mp[i][j] == '.' ? 2 : 0));
      }
    }
    if (ans == 1 << 29)
      cout << -1 << endl;
    else
      cout << ans << endl;
  }
}
