#include <bits/stdc++.h>
using namespace std;
deque<pair<int, int> > dq;
int dist[3][1005][1005], n, m;
char c[1005][1005];
const int inf = 1e8;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
void bfs(int x) {
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      dist[x][i][j] = inf;
    }
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      if (c[i][j] == '1' + x) {
        dq.emplace_back(i, j);
        dist[x][i][j] = 0;
      }
    }
  }
  while (dq.size()) {
    pair<int, int> p = dq.front();
    dq.pop_front();
    int x1 = p.first, y = p.second;
    for (int i = 0; i < 4; ++i) {
      int nx = x1 + dx[i], ny = y + dy[i];
      if (!(nx >= 0 && nx < n && ny >= 0 && ny < m)) {
        continue;
      }
      if (dist[x][nx][ny] != inf || c[nx][ny] == '#') {
        continue;
      }
      int take = (c[nx][ny] == '.');
      dist[x][nx][ny] = dist[x][x1][y] + take;
      if (take) {
        dq.emplace_back(nx, ny);
      } else {
        dq.emplace_front(nx, ny);
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    scanf("%s", c[i]);
  }
  for (int i = 0; i < 3; ++i) {
    bfs(i);
  }
  int ans = inf;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      int cur = dist[0][i][j] + dist[1][i][j] + dist[2][i][j];
      if (c[i][j] == '.') {
        cur -= 2;
      }
      ans = min(ans, cur);
    }
  }
  if (ans >= inf) {
    puts("-1");
  } else {
    cout << ans << endl;
  }
  return 0;
}
