#include <bits/stdc++.h>
using namespace std;
const int N = 1002;
int n, m;
char c[N][N];
int dist[3][N][N];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
inline bool ok(int x, int y) { return (x >= 0 && y >= 0 && x < n && y < m); }
inline void BFS(int t) {
  deque<int> q;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      dist[t - 1][i][j] = 1e9;
      if (c[i][j] == t + '0')
        q.push_back(i), q.push_back(j), dist[t - 1][i][j] = 0;
    }
  }
  while (!q.empty()) {
    int x = q.front();
    q.pop_front();
    int y = q.front();
    q.pop_front();
    for (int i = 0; i < 4; i++) {
      int x2 = x + dx[i];
      int y2 = y + dy[i];
      if (ok(x2, y2) && dist[t - 1][x2][y2] == 1e9 && c[x2][y2] != '#') {
        int f = (c[x2][y2] == '.');
        dist[t - 1][x2][y2] = dist[t - 1][x][y] + f;
        if (f)
          q.push_back(x2), q.push_back(y2);
        else
          q.push_front(y2), q.push_front(x2);
      }
    }
  }
}
int main() {
  for (int k = 0; k < 4; k++)
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) dist[k][i][j] = 1e9;
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> c[i];
  int ans = 1e9;
  for (int i = 1; i <= 3; i++) BFS(i);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      long long pnt = 0;
      if (c[i][j] == '.') pnt -= 2;
      pnt += dist[0][i][j];
      pnt += dist[1][i][j];
      pnt += dist[2][i][j];
      if (pnt >= 1e8) continue;
      ans = min((int)pnt, ans);
    }
  }
  if (ans == 1e9)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}
