#include <bits/stdc++.h>
using namespace std;
char c[1005][1005];
int n, m, vis[1005][1005], dis[1005][1005][4], dx[4] = {0, 0, -1, 1},
                                               dy[4] = {1, -1, 0, 0};
void bfs(int p) {
  memset(vis, 0, sizeof(vis));
  priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>,
                 greater<pair<int, pair<int, int>>>>
      q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (c[i][j] == (char)(p + '0')) {
        q.push({0, {i, j}});
        dis[i][j][p] = 0;
        vis[i][j] = 1;
      }
    }
  }
  while (!q.empty()) {
    int x = q.top().second.first, y = q.top().second.second, d = q.top().first;
    q.pop();
    for (int i = 0; i < 4; i++) {
      int nx = dx[i] + x, ny = dy[i] + y;
      if (nx > n || ny > m || nx < 1 || ny < 1 || c[nx][ny] == '#' ||
          vis[nx][ny])
        continue;
      vis[nx][ny] = 1;
      dis[nx][ny][p] = d + (c[nx][ny] == '.');
      q.push({dis[nx][ny][p], {nx, ny}});
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> c[i][j];
      dis[i][j][1] = dis[i][j][2] = dis[i][j][3] = 1e6 + 5;
    }
  }
  for (int i = 1; i <= 3; i++) {
    bfs(i);
  }
  int ans = 2e9;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      int num = dis[i][j][1] + dis[i][j][2] + dis[i][j][3];
      if (c[i][j] == '.') num -= 2;
      ans = min(ans, num);
    }
  }
  if (ans > 1e6)
    cout << -1 << endl;
  else
    cout << ans << endl;
}
