#include <bits/stdc++.h>
using namespace std;
vector<string> brd(1004);
struct node {
  int x, y;
  int d;
};
bool operator<(node n1, node n2) {
  if (n1.d != n2.d) return n1.d > n2.d;
  if (n1.x != n2.x) return n1.x > n2.x;
  return n1.y > n2.y;
}
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; ++i) cin >> brd[i];
  vector<vector<vector<int> > > dist(
      4, vector<vector<int> >(1003, vector<int>(1003, 100000000)));
  int ans = 1000000000;
  for (int q = 1; q <= 3; q++) {
    vector<vector<bool> > vis(1004, vector<bool>(1004, 0));
    node init = {-1, -1, 0};
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j)
        if (brd[i][j] == q + '0') {
          init.x = i;
          init.y = j;
          break;
        }
    priority_queue<node> myq;
    myq.push(init);
    while (!myq.empty()) {
      node now = myq.top();
      myq.pop();
      if (!vis[now.x][now.y]) {
        vis[now.x][now.y] = 1;
        dist[q][now.x][now.y] = now.d;
        node nxt = now;
        if (now.x > 0) {
          nxt = now;
          nxt.x--;
          if (brd[now.x - 1][now.y] == '.') {
            nxt.d++;
            myq.push(nxt);
          } else if (brd[now.x - 1][now.y] != '#') {
            myq.push(nxt);
          }
        }
        if (now.x < n - 1) {
          nxt = now;
          nxt.x++;
          if (brd[now.x + 1][now.y] == '.') {
            nxt.d++;
            myq.push(nxt);
          } else if (brd[now.x + 1][now.y] != '#') {
            myq.push(nxt);
          }
        }
        if (now.y > 0) {
          nxt = now;
          nxt.y--;
          if (brd[now.x][now.y - 1] == '.') {
            nxt.d++;
            myq.push(nxt);
          } else if (brd[now.x][now.y - 1] != '#') {
            myq.push(nxt);
          }
        }
        if (now.y < m - 1) {
          nxt = now;
          nxt.y++;
          if (brd[now.x][now.y + 1] == '.') {
            nxt.d++;
            myq.push(nxt);
          } else if (brd[now.x][now.y + 1] != '#') {
            myq.push(nxt);
          }
        }
      }
    }
  }
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (brd[i][j] != '#') {
        int x = 0;
        x = dist[1][i][j] + dist[2][i][j] + dist[3][i][j];
        if (brd[i][j] == '.') x -= 2;
        ans = min(x, ans);
      }
  if (ans < 10000000)
    cout << ans << endl;
  else
    cout << "-1\n";
  return 0;
}
