#include <bits/stdc++.h>
using namespace std;
string s[1001];
int n, m;
int dist[3][1001][1001];
int dr[] = {0, 1, 0, -1};
int dc[] = {1, 0, -1, 0};
int fgdgdf[1001][1001];
void compute(int dist[1001][1001], char c) {
  memset(fgdgdf, 0, sizeof fgdgdf);
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) dist[i][j] = 1e8 + 9;
  deque<pair<int, int> > Q;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (s[i][j] == c) dist[i][j] = 0, Q.push_front(make_pair(i, j));
  while (!Q.empty()) {
    int r = Q.front().first;
    int c = Q.front().second;
    Q.pop_front();
    fgdgdf[r][c] += 1;
    if (fgdgdf[r][c] == 2) assert(0);
    for (int k = 0; k < 4; ++k) {
      int nr = r + dr[k];
      int nc = c + dc[k];
      if (nr >= 0 && nr < n && nc >= 0 && nc < m && s[nr][nc] != '#') {
        int cost = (s[nr][nc] == '.');
        if (dist[nr][nc] > dist[r][c] + cost) {
          dist[nr][nc] = dist[r][c] + cost;
          if (cost == 0)
            Q.push_front(make_pair(nr, nc));
          else
            Q.push_back(make_pair(nr, nc));
        }
      }
    }
  }
}
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m;
  for (int i = 0; i < n; ++i) cin >> s[i];
  for (int id = 0; id < 3; ++id) compute(dist[id], '1' + id);
  int ret = 1e8;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (s[i][j] != '#') {
        if (s[i][j] == '.')
          ret = min(ret, dist[0][i][j] + dist[1][i][j] + dist[2][i][j] - 2);
        else
          ret = min(ret, dist[0][i][j] + dist[1][i][j] + dist[2][i][j]);
      }
  if (ret >= 1e8) ret = -1;
  cout << ret;
}
